Natural-Language
stringlengths
13
387
Bash-Command
stringlengths
1
532
Linux-Utilities
stringlengths
5
54
Base-Finetune
stringlengths
108
1.01k
TLDR-Finetune
stringlengths
313
7.3k
Manual-Page-Finetune
stringlengths
861
969k
search for perl files in the folder /users/tom
find /users/tom -name "*.pl"
['find']
Output a Bash command to accomplish the following task. Task: search for perl files in the folder /users/tom Bash Command:<START>find /users/tom -name "*.pl"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for perl files in the folder /users/tom Bash Command:<START>find /users/tom -name "*.pl"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for perl files in the folder /users/tom Bash Command:<START>find /users/tom -name "*.pl"<END>
search for regular files in the current folder which path is not "./.*" and not "./*/.*"
find ./ -type f -name "*" ! -path "./.*" ! -path "./*/.*"
['find']
Output a Bash command to accomplish the following task. Task: search for regular files in the current folder which path is not "./.*" and not "./*/.*" Bash Command:<START>find ./ -type f -name "*" ! -path "./.*" ! -path "./*/.*"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for regular files in the current folder which path is not "./.*" and not "./*/.*" Bash Command:<START>find ./ -type f -name "*" ! -path "./.*" ! -path "./*/.*"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for regular files in the current folder which path is not "./.*" and not "./*/.*" Bash Command:<START>find ./ -type f -name "*" ! -path "./.*" ! -path "./*/.*"<END>
search for regular/normal file with the name "myfile" in the entire file system
find / -name myfile -type f -print
['find']
Output a Bash command to accomplish the following task. Task: search for regular/normal file with the name "myfile" in the entire file system Bash Command:<START>find / -name myfile -type f -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for regular/normal file with the name "myfile" in the entire file system Bash Command:<START>find / -name myfile -type f -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for regular/normal file with the name "myfile" in the entire file system Bash Command:<START>find / -name myfile -type f -print<END>
search for soft links in current folder and display those links which are not pointed to files in current folder
find . -type l -exec readlink -f '{}' \; | grep -v "^`readlink -f ${PWD}`"
['find', 'grep', 'readlink']
Output a Bash command to accomplish the following task. Task: search for soft links in current folder and display those links which are not pointed to files in current folder Bash Command:<START>find . -type l -exec readlink -f '{}' \; | grep -v "^`readlink -f ${PWD}`"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n # readlink\n\n> Follow symlinks and get symlink information.\n> More information: <https://www.gnu.org/software/coreutils/readlink>.\n\n- Get the actual file to which the symlink points:\n\n`readlink {{path/to/file}}`\n\n- Get the absolute path to a file:\n\n`readlink -f {{path/to/file}}`\n Task: search for soft links in current folder and display those links which are not pointed to files in current folder Bash Command:<START>find . -type l -exec readlink -f '{}' \; | grep -v "^`readlink -f ${PWD}`"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. readlink(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training readlink(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON READLINK(1) User Commands READLINK(1) NAME top readlink - print resolved symbolic links or canonical file names SYNOPSIS top readlink [OPTION]... FILE... DESCRIPTION top Note realpath(1) is the preferred command to use for canonicalization functionality. Print value of a symbolic link or canonical file name -f, --canonicalize canonicalize by following every symlink in every component of the given name recursively; all but the last component must exist -e, --canonicalize-existing canonicalize by following every symlink in every component of the given name recursively, all components must exist -m, --canonicalize-missing canonicalize by following every symlink in every component of the given name recursively, without requirements on components existence -n, --no-newline do not output the trailing delimiter -q, --quiet -s, --silent suppress most error messages (on by default) -v, --verbose report error messages -z, --zero end each output line with NUL, not newline --help display this help and exit --version output version information and exit AUTHOR top Written by Dmitry V. Levin. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top readlink(2), realpath(1), realpath(3) Full documentation <https://www.gnu.org/software/coreutils/readlink> or available locally via: info '(coreutils) readlink invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 READLINK(1) Pages that refer to this page: basename(1), dirname(1), dpkg-realpath(1), realpath(1), unshare(1), mount(2), readlink(2), unshare(2), namespaces(7), mount(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for soft links in current folder and display those links which are not pointed to files in current folder Bash Command:<START>find . -type l -exec readlink -f '{}' \; | grep -v "^`readlink -f ${PWD}`"<END>
search for swap files (.swp files) in temp folder and remove them
find /tmp -name '*.swp' -exec rm {} \;
['find', 'rm']
Output a Bash command to accomplish the following task. Task: search for swap files (.swp files) in temp folder and remove them Bash Command:<START>find /tmp -name '*.swp' -exec rm {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # rm\n\n> Remove files or directories.\n> See also: `rmdir`.\n> More information: <https://www.gnu.org/software/coreutils/rm>.\n\n- Remove specific files:\n\n`rm {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files ignoring nonexistent ones:\n\n`rm --force {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files interactively prompting before each removal:\n\n`rm --interactive {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files printing info about each removal:\n\n`rm --verbose {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files and directories recursively:\n\n`rm --recursive {{path/to/file_or_directory1 path/to/file_or_directory2 ...}}`\n Task: search for swap files (.swp files) in temp folder and remove them Bash Command:<START>find /tmp -name '*.swp' -exec rm {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. rm(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training rm(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON RM(1) User Commands RM(1) NAME top rm - remove files or directories SYNOPSIS top rm [OPTION]... [FILE]... DESCRIPTION top This manual page documents the GNU version of rm. rm removes each specified file. By default, it does not remove directories. If the -I or --interactive=once option is given, and there are more than three files or the -r, -R, or --recursive are given, then rm prompts the user for whether to proceed with the entire operation. If the response is not affirmative, the entire command is aborted. Otherwise, if a file is unwritable, standard input is a terminal, and the -f or --force option is not given, or the -i or --interactive=always option is given, rm prompts the user for whether to remove the file. If the response is not affirmative, the file is skipped. OPTIONS top Remove (unlink) the FILE(s). -f, --force ignore nonexistent files and arguments, never prompt -i prompt before every removal -I prompt once before removing more than three files, or when removing recursively; less intrusive than -i, while still giving protection against most mistakes --interactive[=WHEN] prompt according to WHEN: never, once (-I), or always (-i); without WHEN, prompt always --one-file-system when removing a hierarchy recursively, skip any directory that is on a file system different from that of the corresponding command line argument --no-preserve-root do not treat '/' specially --preserve-root[=all] do not remove '/' (default); with 'all', reject any command line argument on a separate device from its parent -r, -R, --recursive remove directories and their contents recursively -d, --dir remove empty directories -v, --verbose explain what is being done --help display this help and exit --version output version information and exit By default, rm does not remove directories. Use the --recursive (-r or -R) option to remove each listed directory, too, along with all of its contents. To remove a file whose name starts with a '-', for example '-foo', use one of these commands: rm -- -foo rm ./-foo Note that if you use rm to remove a file, it might be possible to recover some of its contents, given sufficient expertise and/or time. For greater assurance that the contents are truly unrecoverable, consider using shred(1). AUTHOR top Written by Paul Rubin, David MacKenzie, Richard M. Stallman, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top unlink(1), unlink(2), chattr(1), shred(1) Full documentation <https://www.gnu.org/software/coreutils/rm> or available locally via: info '(coreutils) rm invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 RM(1) Pages that refer to this page: rmdir(2), unlink(2), remove(3), mq_overview(7), symlink(7), debugfs(8), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for swap files (.swp files) in temp folder and remove them Bash Command:<START>find /tmp -name '*.swp' -exec rm {} \;<END>
search for text files in the current folder which have write access to others
find . -type f \( -iname "*.txt" -and -perm -o=w \)
['find']
Output a Bash command to accomplish the following task. Task: search for text files in the current folder which have write access to others Bash Command:<START>find . -type f \( -iname "*.txt" -and -perm -o=w \)<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for text files in the current folder which have write access to others Bash Command:<START>find . -type f \( -iname "*.txt" -and -perm -o=w \)<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for text files in the current folder which have write access to others Bash Command:<START>find . -type f \( -iname "*.txt" -and -perm -o=w \)<END>
search for text files in the directory "/home/user1" and copy them to the directory /home/backup
find /home/user1 -name '*.txt' | xargs cp -av --target-directory=/home/backup/ --parents
['find', 'xargs', 'cp']
Output a Bash command to accomplish the following task. Task: search for text files in the directory "/home/user1" and copy them to the directory /home/backup Bash Command:<START>find /home/user1 -name '*.txt' | xargs cp -av --target-directory=/home/backup/ --parents<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: search for text files in the directory "/home/user1" and copy them to the directory /home/backup Bash Command:<START>find /home/user1 -name '*.txt' | xargs cp -av --target-directory=/home/backup/ --parents<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for text files in the directory "/home/user1" and copy them to the directory /home/backup Bash Command:<START>find /home/user1 -name '*.txt' | xargs cp -av --target-directory=/home/backup/ --parents<END>
search for text files in the folder /home/you which have been modified in the last 60*24 hours(case insensitive search) and display their contents
find /home/you -iname "*.txt" -mtime -60 -exec cat {} \;
['find', 'cat']
Output a Bash command to accomplish the following task. Task: search for text files in the folder /home/you which have been modified in the last 60*24 hours(case insensitive search) and display their contents Bash Command:<START>find /home/you -iname "*.txt" -mtime -60 -exec cat {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # cat\n\n> Print and concatenate files.\n> More information: <https://www.gnu.org/software/coreutils/cat>.\n\n- Print the contents of a file to `stdout`:\n\n`cat {{path/to/file}}`\n\n- Concatenate several files into an output file:\n\n`cat {{path/to/file1 path/to/file2 ...}} > {{path/to/output_file}}`\n\n- Append several files to an output file:\n\n`cat {{path/to/file1 path/to/file2 ...}} >> {{path/to/output_file}}`\n\n- Write `stdin` to a file:\n\n`cat - > {{path/to/file}}`\n\n- [n]umber all output lines:\n\n`cat -n {{path/to/file}}`\n\n- Display non-printable and whitespace characters (with `M-` prefix if non-ASCII):\n\n`cat -v -t -e {{path/to/file}}`\n Task: search for text files in the folder /home/you which have been modified in the last 60*24 hours(case insensitive search) and display their contents Bash Command:<START>find /home/you -iname "*.txt" -mtime -60 -exec cat {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cat(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cat(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | EXAMPLES | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CAT(1) User Commands CAT(1) NAME top cat - concatenate files and print on the standard output SYNOPSIS top cat [OPTION]... [FILE]... DESCRIPTION top Concatenate FILE(s) to standard output. With no FILE, or when FILE is -, read standard input. -A, --show-all equivalent to -vET -b, --number-nonblank number nonempty output lines, overrides -n -e equivalent to -vE -E, --show-ends display $ at end of each line -n, --number number all output lines -s, --squeeze-blank suppress repeated empty output lines -t equivalent to -vT -T, --show-tabs display TAB characters as ^I -u (ignored) -v, --show-nonprinting use ^ and M- notation, except for LFD and TAB --help display this help and exit --version output version information and exit EXAMPLES top cat f - g Output f's contents, then standard input, then g's contents. cat Copy standard input to standard output. AUTHOR top Written by Torbjorn Granlund and Richard M. Stallman. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top tac(1) Full documentation <https://www.gnu.org/software/coreutils/cat> or available locally via: info '(coreutils) cat invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CAT(1) Pages that refer to this page: pmlogrewrite(1), pv(1), systemd-socket-activate(1), tac(1), ul(1), proc(5), cpuset(7), time_namespaces(7), readprofile(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for text files in the folder /home/you which have been modified in the last 60*24 hours(case insensitive search) and display their contents Bash Command:<START>find /home/you -iname "*.txt" -mtime -60 -exec cat {} \;<END>
search for text files in the folders /home/hobbes/ /home/calvin/
find /home/hobbes/ /home/calvin/ -name “*.txt”
['find']
Output a Bash command to accomplish the following task. Task: search for text files in the folders /home/hobbes/ /home/calvin/ Bash Command:<START>find /home/hobbes/ /home/calvin/ -name “*.txt”<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for text files in the folders /home/hobbes/ /home/calvin/ Bash Command:<START>find /home/hobbes/ /home/calvin/ -name “*.txt”<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for text files in the folders /home/hobbes/ /home/calvin/ Bash Command:<START>find /home/hobbes/ /home/calvin/ -name “*.txt”<END>
search for the directory "config" in the current folder
find . -name config -type d
['find']
Output a Bash command to accomplish the following task. Task: search for the directory "config" in the current folder Bash Command:<START>find . -name config -type d<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the directory "config" in the current folder Bash Command:<START>find . -name config -type d<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the directory "config" in the current folder Bash Command:<START>find . -name config -type d<END>
search for the directory "config" in the current folder and change directory to it
cd `find . -name "config"`
['find', 'cd']
Output a Bash command to accomplish the following task. Task: search for the directory "config" in the current folder and change directory to it Bash Command:<START>cd `find . -name "config"`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # cd\n\n> Change the current working directory.\n> More information: <https://manned.org/cd>.\n\n- Go to the specified directory:\n\n`cd {{path/to/directory}}`\n\n- Go up to the parent of the current directory:\n\n`cd ..`\n\n- Go to the home directory of the current user:\n\n`cd`\n\n- Go to the home directory of the specified user:\n\n`cd ~{{username}}`\n\n- Go to the previously chosen directory:\n\n`cd -`\n\n- Go to the root directory:\n\n`cd /`\n Task: search for the directory "config" in the current folder and change directory to it Bash Command:<START>cd `find . -name "config"`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cd(1p) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cd(1p) Linux manual page PROLOG | NAME | SYNOPSIS | DESCRIPTION | OPTIONS | OPERANDS | STDIN | INPUT FILES | ENVIRONMENT VARIABLES | ASYNCHRONOUS EVENTS | STDOUT | STDERR | OUTPUT FILES | EXTENDED DESCRIPTION | EXIT STATUS | CONSEQUENCES OF ERRORS | APPLICATION USAGE | EXAMPLES | RATIONALE | FUTURE DIRECTIONS | SEE ALSO | COPYRIGHT CD(1P) POSIX Programmer's Manual CD(1P) PROLOG top 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. NAME top cd change the working directory SYNOPSIS top cd [-L|-P] [directory] cd - DESCRIPTION top The cd utility shall change the working directory of the current shell execution environment (see Section 2.12, Shell Execution Environment) by executing the following steps in sequence. (In the following steps, the symbol curpath represents an intermediate value used to simplify the description of the algorithm used by cd. There is no requirement that curpath be made visible to the application.) 1. If no directory operand is given and the HOME environment variable is empty or undefined, the default behavior is implementation-defined and no further steps shall be taken. 2. If no directory operand is given and the HOME environment variable is set to a non-empty value, the cd utility shall behave as if the directory named in the HOME environment variable was specified as the directory operand. 3. If the directory operand begins with a <slash> character, set curpath to the operand and proceed to step 7. 4. If the first component of the directory operand is dot or dot-dot, proceed to step 6. 5. Starting with the first pathname in the <colon>-separated pathnames of CDPATH (see the ENVIRONMENT VARIABLES section) if the pathname is non-null, test if the concatenation of that pathname, a <slash> character if that pathname did not end with a <slash> character, and the directory operand names a directory. If the pathname is null, test if the concatenation of dot, a <slash> character, and the operand names a directory. In either case, if the resulting string names an existing directory, set curpath to that string and proceed to step 7. Otherwise, repeat this step with the next pathname in CDPATH until all pathnames have been tested. 6. Set curpath to the directory operand. 7. If the -P option is in effect, proceed to step 10. If curpath does not begin with a <slash> character, set curpath to the string formed by the concatenation of the value of PWD, a <slash> character if the value of PWD did not end with a <slash> character, and curpath. 8. The curpath value shall then be converted to canonical form as follows, considering each component from beginning to end, in sequence: a. Dot components and any <slash> characters that separate them from the next component shall be deleted. b. For each dot-dot component, if there is a preceding component and it is neither root nor dot-dot, then: i. If the preceding component does not refer (in the context of pathname resolution with symbolic links followed) to a directory, then the cd utility shall display an appropriate error message and no further steps shall be taken. ii. The preceding component, all <slash> characters separating the preceding component from dot-dot, dot-dot, and all <slash> characters separating dot- dot from the following component (if any) shall be deleted. c. An implementation may further simplify curpath by removing any trailing <slash> characters that are not also leading <slash> characters, replacing multiple non- leading consecutive <slash> characters with a single <slash>, and replacing three or more leading <slash> characters with a single <slash>. If, as a result of this canonicalization, the curpath variable is null, no further steps shall be taken. 9. If curpath is longer than {PATH_MAX} bytes (including the terminating null) and the directory operand was not longer than {PATH_MAX} bytes (including the terminating null), then curpath shall be converted from an absolute pathname to an equivalent relative pathname if possible. This conversion shall always be considered possible if the value of PWD, with a trailing <slash> added if it does not already have one, is an initial substring of curpath. Whether or not it is considered possible under other circumstances is unspecified. Implementations may also apply this conversion if curpath is not longer than {PATH_MAX} bytes or the directory operand was longer than {PATH_MAX} bytes. 10. The cd utility shall then perform actions equivalent to the chdir() function called with curpath as the path argument. If these actions fail for any reason, the cd utility shall display an appropriate error message and the remainder of this step shall not be executed. If the -P option is not in effect, the PWD environment variable shall be set to the value that curpath had on entry to step 9 (i.e., before conversion to a relative pathname). If the -P option is in effect, the PWD environment variable shall be set to the string that would be output by pwd -P. If there is insufficient permission on the new directory, or on any parent of that directory, to determine the current working directory, the value of the PWD environment variable is unspecified. If, during the execution of the above steps, the PWD environment variable is set, the OLDPWD environment variable shall also be set to the value of the old working directory (that is the current working directory immediately prior to the call to cd). OPTIONS top The cd utility shall conform to the Base Definitions volume of POSIX.12017, Section 12.2, Utility Syntax Guidelines. The following options shall be supported by the implementation: -L Handle the operand dot-dot logically; symbolic link components shall not be resolved before dot-dot components are processed (see steps 8. and 9. in the DESCRIPTION). -P Handle the operand dot-dot physically; symbolic link components shall be resolved before dot-dot components are processed (see step 7. in the DESCRIPTION). If both -L and -P options are specified, the last of these options shall be used and all others ignored. If neither -L nor -P is specified, the operand shall be handled dot-dot logically; see the DESCRIPTION. OPERANDS top The following operands shall be supported: directory An absolute or relative pathname of the directory that shall become the new working directory. The interpretation of a relative pathname by cd depends on the -L option and the CDPATH and PWD environment variables. If directory is an empty string, the results are unspecified. - When a <hyphen-minus> is used as the operand, this shall be equivalent to the command: cd "$OLDPWD" && pwd which changes to the previous working directory and then writes its name. STDIN top Not used. INPUT FILES top None. ENVIRONMENT VARIABLES top The following environment variables shall affect the execution of cd: CDPATH A <colon>-separated list of pathnames that refer to directories. The cd utility shall use this list in its attempt to change the directory, as described in the DESCRIPTION. An empty string in place of a directory pathname represents the current directory. If CDPATH is not set, it shall be treated as if it were an empty string. HOME The name of the directory, used when no directory operand is specified. LANG Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of POSIX.12017, 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, override the values of all the other internationalization variables. LC_CTYPE Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments). LC_MESSAGES Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error. NLSPATH Determine the location of message catalogs for the processing of LC_MESSAGES. OLDPWD A pathname of the previous working directory, used by cd -. PWD This variable shall be set as specified in the DESCRIPTION. If an application sets or unsets the value of PWD, the behavior of cd is unspecified. ASYNCHRONOUS EVENTS top Default. STDOUT top If a non-empty directory name from CDPATH is used, or if cd - is used, an absolute pathname of the new working directory shall be written to the standard output as follows: "%s\n", <new directory> Otherwise, there shall be no output. STDERR top The standard error shall be used only for diagnostic messages. OUTPUT FILES top None. EXTENDED DESCRIPTION top None. EXIT STATUS top The following exit values shall be returned: 0 The directory was successfully changed. >0 An error occurred. CONSEQUENCES OF ERRORS top The working directory shall remain unchanged. The following sections are informative. APPLICATION USAGE top Since cd affects the current shell execution environment, it is always provided as a shell regular built-in. If it is called in a subshell or separate utility execution environment, such as one of the following: (cd /tmp) nohup cd find . -exec cd {} \; it does not affect the working directory of the caller's environment. The user must have execute (search) permission in directory in order to change to it. EXAMPLES top The following template can be used to perform processing in the directory specified by location and end up in the current working directory in use before the first cd command was issued: cd location if [ $? -ne 0 ] then print error message exit 1 fi ... do whatever is desired as long as the OLDPWD environment variable is not modified cd - RATIONALE top The use of the CDPATH was introduced in the System V shell. Its use is analogous to the use of the PATH variable in the shell. The BSD C shell used a shell parameter cdpath for this purpose. A common extension when HOME is undefined is to get the login directory from the user database for the invoking user. This does not occur on System V implementations. Some historical shells, such as the KornShell, took special actions when the directory name contained a dot-dot component, selecting the logical parent of the directory, rather than the actual parent directory; that is, it moved up one level toward the '/' in the pathname, remembering what the user typed, rather than performing the equivalent of: chdir(".."); In such a shell, the following commands would not necessarily produce equivalent output for all directories: cd .. && ls ls .. This behavior is now the default. It is not consistent with the definition of dot-dot in most historical practice; that is, while this behavior has been optionally available in the KornShell, other shells have historically not supported this functionality. The logical pathname is stored in the PWD environment variable when the cd utility completes and this value is used to construct the next directory name if cd is invoked with the -L option. FUTURE DIRECTIONS top None. SEE ALSO top Section 2.12, Shell Execution Environment, pwd(1p) The Base Definitions volume of POSIX.12017, Chapter 8, Environment Variables, Section 12.2, Utility Syntax Guidelines The System Interfaces volume of POSIX.12017, chdir(3p) COPYRIGHT top 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 . IEEE/The Open Group 2017 CD(1P) Pages that refer to this page: pwd(1p), sh(1p) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the directory "config" in the current folder and change directory to it Bash Command:<START>cd `find . -name "config"`<END>
search for the directory "config" in the current folder and change directory to the first instance of the search
cd $(find . -name config -type d | sed 1q)
['find', 'cd', 'sed']
Output a Bash command to accomplish the following task. Task: search for the directory "config" in the current folder and change directory to the first instance of the search Bash Command:<START>cd $(find . -name config -type d | sed 1q)<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # cd\n\n> Change the current working directory.\n> More information: <https://manned.org/cd>.\n\n- Go to the specified directory:\n\n`cd {{path/to/directory}}`\n\n- Go up to the parent of the current directory:\n\n`cd ..`\n\n- Go to the home directory of the current user:\n\n`cd`\n\n- Go to the home directory of the specified user:\n\n`cd ~{{username}}`\n\n- Go to the previously chosen directory:\n\n`cd -`\n\n- Go to the root directory:\n\n`cd /`\n # sed\n\n> Edit text in a scriptable manner.\n> See also: `awk`, `ed`.\n> More information: <https://www.gnu.org/software/sed/manual/sed.html>.\n\n- Replace all `apple` (basic regex) occurrences with `mango` (basic regex) in all input lines and print the result to `stdout`:\n\n`{{command}} | sed 's/apple/mango/g'`\n\n- Replace all `apple` (extended regex) occurrences with `APPLE` (extended regex) in all input lines and print the result to `stdout`:\n\n`{{command}} | sed -E 's/(apple)/\U\1/g'`\n\n- Replace all `apple` (basic regex) occurrences with `mango` (basic regex) in a specific file and overwrite the original file in place:\n\n`sed -i 's/apple/mango/g' {{path/to/file}}`\n\n- Execute a specific script [f]ile and print the result to `stdout`:\n\n`{{command}} | sed -f {{path/to/script.sed}}`\n\n- Print just the first line to `stdout`:\n\n`{{command}} | sed -n '1p'`\n\n- [d]elete the first line of a file:\n\n`sed -i 1d {{path/to/file}}`\n\n- [i]nsert a new line at the first line of a file:\n\n`sed -i '1i\your new line text\' {{path/to/file}}`\n Task: search for the directory "config" in the current folder and change directory to the first instance of the search Bash Command:<START>cd $(find . -name config -type d | sed 1q)<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cd(1p) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cd(1p) Linux manual page PROLOG | NAME | SYNOPSIS | DESCRIPTION | OPTIONS | OPERANDS | STDIN | INPUT FILES | ENVIRONMENT VARIABLES | ASYNCHRONOUS EVENTS | STDOUT | STDERR | OUTPUT FILES | EXTENDED DESCRIPTION | EXIT STATUS | CONSEQUENCES OF ERRORS | APPLICATION USAGE | EXAMPLES | RATIONALE | FUTURE DIRECTIONS | SEE ALSO | COPYRIGHT CD(1P) POSIX Programmer's Manual CD(1P) PROLOG top 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. NAME top cd change the working directory SYNOPSIS top cd [-L|-P] [directory] cd - DESCRIPTION top The cd utility shall change the working directory of the current shell execution environment (see Section 2.12, Shell Execution Environment) by executing the following steps in sequence. (In the following steps, the symbol curpath represents an intermediate value used to simplify the description of the algorithm used by cd. There is no requirement that curpath be made visible to the application.) 1. If no directory operand is given and the HOME environment variable is empty or undefined, the default behavior is implementation-defined and no further steps shall be taken. 2. If no directory operand is given and the HOME environment variable is set to a non-empty value, the cd utility shall behave as if the directory named in the HOME environment variable was specified as the directory operand. 3. If the directory operand begins with a <slash> character, set curpath to the operand and proceed to step 7. 4. If the first component of the directory operand is dot or dot-dot, proceed to step 6. 5. Starting with the first pathname in the <colon>-separated pathnames of CDPATH (see the ENVIRONMENT VARIABLES section) if the pathname is non-null, test if the concatenation of that pathname, a <slash> character if that pathname did not end with a <slash> character, and the directory operand names a directory. If the pathname is null, test if the concatenation of dot, a <slash> character, and the operand names a directory. In either case, if the resulting string names an existing directory, set curpath to that string and proceed to step 7. Otherwise, repeat this step with the next pathname in CDPATH until all pathnames have been tested. 6. Set curpath to the directory operand. 7. If the -P option is in effect, proceed to step 10. If curpath does not begin with a <slash> character, set curpath to the string formed by the concatenation of the value of PWD, a <slash> character if the value of PWD did not end with a <slash> character, and curpath. 8. The curpath value shall then be converted to canonical form as follows, considering each component from beginning to end, in sequence: a. Dot components and any <slash> characters that separate them from the next component shall be deleted. b. For each dot-dot component, if there is a preceding component and it is neither root nor dot-dot, then: i. If the preceding component does not refer (in the context of pathname resolution with symbolic links followed) to a directory, then the cd utility shall display an appropriate error message and no further steps shall be taken. ii. The preceding component, all <slash> characters separating the preceding component from dot-dot, dot-dot, and all <slash> characters separating dot- dot from the following component (if any) shall be deleted. c. An implementation may further simplify curpath by removing any trailing <slash> characters that are not also leading <slash> characters, replacing multiple non- leading consecutive <slash> characters with a single <slash>, and replacing three or more leading <slash> characters with a single <slash>. If, as a result of this canonicalization, the curpath variable is null, no further steps shall be taken. 9. If curpath is longer than {PATH_MAX} bytes (including the terminating null) and the directory operand was not longer than {PATH_MAX} bytes (including the terminating null), then curpath shall be converted from an absolute pathname to an equivalent relative pathname if possible. This conversion shall always be considered possible if the value of PWD, with a trailing <slash> added if it does not already have one, is an initial substring of curpath. Whether or not it is considered possible under other circumstances is unspecified. Implementations may also apply this conversion if curpath is not longer than {PATH_MAX} bytes or the directory operand was longer than {PATH_MAX} bytes. 10. The cd utility shall then perform actions equivalent to the chdir() function called with curpath as the path argument. If these actions fail for any reason, the cd utility shall display an appropriate error message and the remainder of this step shall not be executed. If the -P option is not in effect, the PWD environment variable shall be set to the value that curpath had on entry to step 9 (i.e., before conversion to a relative pathname). If the -P option is in effect, the PWD environment variable shall be set to the string that would be output by pwd -P. If there is insufficient permission on the new directory, or on any parent of that directory, to determine the current working directory, the value of the PWD environment variable is unspecified. If, during the execution of the above steps, the PWD environment variable is set, the OLDPWD environment variable shall also be set to the value of the old working directory (that is the current working directory immediately prior to the call to cd). OPTIONS top The cd utility shall conform to the Base Definitions volume of POSIX.12017, Section 12.2, Utility Syntax Guidelines. The following options shall be supported by the implementation: -L Handle the operand dot-dot logically; symbolic link components shall not be resolved before dot-dot components are processed (see steps 8. and 9. in the DESCRIPTION). -P Handle the operand dot-dot physically; symbolic link components shall be resolved before dot-dot components are processed (see step 7. in the DESCRIPTION). If both -L and -P options are specified, the last of these options shall be used and all others ignored. If neither -L nor -P is specified, the operand shall be handled dot-dot logically; see the DESCRIPTION. OPERANDS top The following operands shall be supported: directory An absolute or relative pathname of the directory that shall become the new working directory. The interpretation of a relative pathname by cd depends on the -L option and the CDPATH and PWD environment variables. If directory is an empty string, the results are unspecified. - When a <hyphen-minus> is used as the operand, this shall be equivalent to the command: cd "$OLDPWD" && pwd which changes to the previous working directory and then writes its name. STDIN top Not used. INPUT FILES top None. ENVIRONMENT VARIABLES top The following environment variables shall affect the execution of cd: CDPATH A <colon>-separated list of pathnames that refer to directories. The cd utility shall use this list in its attempt to change the directory, as described in the DESCRIPTION. An empty string in place of a directory pathname represents the current directory. If CDPATH is not set, it shall be treated as if it were an empty string. HOME The name of the directory, used when no directory operand is specified. LANG Provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of POSIX.12017, 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, override the values of all the other internationalization variables. LC_CTYPE Determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments). LC_MESSAGES Determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error. NLSPATH Determine the location of message catalogs for the processing of LC_MESSAGES. OLDPWD A pathname of the previous working directory, used by cd -. PWD This variable shall be set as specified in the DESCRIPTION. If an application sets or unsets the value of PWD, the behavior of cd is unspecified. ASYNCHRONOUS EVENTS top Default. STDOUT top If a non-empty directory name from CDPATH is used, or if cd - is used, an absolute pathname of the new working directory shall be written to the standard output as follows: "%s\n", <new directory> Otherwise, there shall be no output. STDERR top The standard error shall be used only for diagnostic messages. OUTPUT FILES top None. EXTENDED DESCRIPTION top None. EXIT STATUS top The following exit values shall be returned: 0 The directory was successfully changed. >0 An error occurred. CONSEQUENCES OF ERRORS top The working directory shall remain unchanged. The following sections are informative. APPLICATION USAGE top Since cd affects the current shell execution environment, it is always provided as a shell regular built-in. If it is called in a subshell or separate utility execution environment, such as one of the following: (cd /tmp) nohup cd find . -exec cd {} \; it does not affect the working directory of the caller's environment. The user must have execute (search) permission in directory in order to change to it. EXAMPLES top The following template can be used to perform processing in the directory specified by location and end up in the current working directory in use before the first cd command was issued: cd location if [ $? -ne 0 ] then print error message exit 1 fi ... do whatever is desired as long as the OLDPWD environment variable is not modified cd - RATIONALE top The use of the CDPATH was introduced in the System V shell. Its use is analogous to the use of the PATH variable in the shell. The BSD C shell used a shell parameter cdpath for this purpose. A common extension when HOME is undefined is to get the login directory from the user database for the invoking user. This does not occur on System V implementations. Some historical shells, such as the KornShell, took special actions when the directory name contained a dot-dot component, selecting the logical parent of the directory, rather than the actual parent directory; that is, it moved up one level toward the '/' in the pathname, remembering what the user typed, rather than performing the equivalent of: chdir(".."); In such a shell, the following commands would not necessarily produce equivalent output for all directories: cd .. && ls ls .. This behavior is now the default. It is not consistent with the definition of dot-dot in most historical practice; that is, while this behavior has been optionally available in the KornShell, other shells have historically not supported this functionality. The logical pathname is stored in the PWD environment variable when the cd utility completes and this value is used to construct the next directory name if cd is invoked with the -L option. FUTURE DIRECTIONS top None. SEE ALSO top Section 2.12, Shell Execution Environment, pwd(1p) The Base Definitions volume of POSIX.12017, Chapter 8, Environment Variables, Section 12.2, Utility Syntax Guidelines The System Interfaces volume of POSIX.12017, chdir(3p) COPYRIGHT top 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 . IEEE/The Open Group 2017 CD(1P) Pages that refer to this page: pwd(1p), sh(1p) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. sed(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training sed(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | COMMAND SYNOPSIS | REGULAR EXPRESSIONS | BUGS | AUTHOR | COPYRIGHT | SEE ALSO | COLOPHON SED(1) User Commands SED(1) NAME top sed - stream editor for filtering and transforming text SYNOPSIS top sed [-V] [--version] [--help] [-n] [--quiet] [--silent] [-l N] [--line-length=N] [-u] [--unbuffered] [-E] [-r] [--regexp-extended] [-e script] [--expression=script] [-f script-file] [--file=script-file] [script-if-no-other-script] [file...] DESCRIPTION top Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed's ability to filter text in a pipeline which particularly distinguishes it from other types of editors. -n, --quiet, --silent suppress automatic printing of pattern space --debug annotate program execution -e script, --expression=script add the script to the commands to be executed -f script-file, --file=script-file add the contents of script-file to the commands to be executed --follow-symlinks follow symlinks when processing in place -i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if SUFFIX supplied) -l N, --line-length=N specify the desired line-wrap length for the `l' command --posix disable all GNU extensions. -E, -r, --regexp-extended use extended regular expressions in the script (for portability use POSIX -E). -s, --separate consider files as separate rather than as a single, continuous long stream. --sandbox operate in sandbox mode (disable e/r/w commands). -u, --unbuffered load minimal amounts of data from the input files and flush the output buffers more often -z, --null-data separate lines by NUL characters --help display this help and exit --version output version information and exit If no -e, --expression, -f, or --file option is given, then the first non-option argument is taken as the sed script to interpret. All remaining arguments are names of input files; if no input files are specified, then the standard input is read. GNU sed home page: <https://www.gnu.org/software/sed/>. General help using GNU software: <https://www.gnu.org/gethelp/>. E-mail bug reports to: <bug-sed@gnu.org>. COMMAND SYNOPSIS top This is just a brief synopsis of sed commands to serve as a reminder to those who already know sed; other documentation (such as the texinfo document) must be consulted for fuller descriptions. Zero-address ``commands'' : label Label for b and t commands. #comment The comment extends until the next newline (or the end of a -e script fragment). } The closing bracket of a { } block. Zero- or One- address commands = Print the current line number. a \ text Append text, which has each embedded newline preceded by a backslash. i \ text Insert text, which has each embedded newline preceded by a backslash. q [exit-code] Immediately quit the sed script without processing any more input, except that if auto-print is not disabled the current pattern space will be printed. The exit code argument is a GNU extension. Q [exit-code] Immediately quit the sed script without processing any more input. This is a GNU extension. r filename Append text read from filename. R filename Append a line read from filename. Each invocation of the command reads a line from the file. This is a GNU extension. Commands which accept address ranges { Begin a block of commands (end with a }). b label Branch to label; if label is omitted, branch to end of script. c \ text Replace the selected lines with text, which has each embedded newline preceded by a backslash. d Delete pattern space. Start next cycle. D If pattern space contains no newline, start a normal new cycle as if the d command was issued. Otherwise, delete text in the pattern space up to the first newline, and restart cycle with the resultant pattern space, without reading a new line of input. h H Copy/append pattern space to hold space. g G Copy/append hold space to pattern space. l List out the current line in a ``visually unambiguous'' form. l width List out the current line in a ``visually unambiguous'' form, breaking it at width characters. This is a GNU extension. n N Read/append the next line of input into the pattern space. p Print the current pattern space. P Print up to the first embedded newline of the current pattern space. s/regexp/replacement/ Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement. The replacement may contain the special character & to refer to that portion of the pattern space which matched, and the special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp. t label If a s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script. T label If no s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script. This is a GNU extension. w filename Write the current pattern space to filename. W filename Write the first line of the current pattern space to filename. This is a GNU extension. x Exchange the contents of the hold and pattern spaces. y/source/dest/ Transliterate the characters in the pattern space which appear in source to the corresponding character in dest. Addresses Sed commands can be given with no addresses, in which case the command will be executed for all input lines; with one address, in which case the command will only be executed for input lines which match that address; or with two addresses, in which case the command will be executed for all input lines which match the inclusive range of lines starting from the first address and continuing to the second address. Three things to note about address ranges: the syntax is addr1,addr2 (i.e., the addresses are separated by a comma); the line which addr1 matched will always be accepted, even if addr2 selects an earlier line; and if addr2 is a regexp, it will not be tested against the line that addr1 matched. After the address (or address-range), and before the command, a ! may be inserted, which specifies that the command shall only be executed if the address (or address-range) does not match. The following address types are supported: number Match only the specified line number (which increments cumulatively across files, unless the -s option is specified on the command line). first~step Match every step'th line starting with line first. For example, ``sed -n 1~2p'' will print all the odd-numbered lines in the input stream, and the address 2~5 will match every fifth line, starting with the second. first can be zero; in this case, sed operates as if it were equal to step. (This is an extension.) $ Match the last line. /regexp/ Match lines matching the regular expression regexp. Matching is performed on the current pattern space, which can be modified with commands such as ``s///''. \cregexpc Match lines matching the regular expression regexp. The c may be any character. GNU sed also supports some special 2-address forms: 0,addr2 Start out in "matched first address" state, until addr2 is found. This is similar to 1,addr2, except that if addr2 matches the very first line of input the 0,addr2 form will be at the end of its range, whereas the 1,addr2 form will still be at the beginning of its range. This works only when addr2 is a regular expression. addr1,+N Will match addr1 and the N lines following addr1. addr1,~N Will match addr1 and the lines following addr1 until the next line whose input line number is a multiple of N. REGULAR EXPRESSIONS top POSIX.2 BREs should be supported, but they aren't completely because of performance problems. The \n sequence in a regular expression matches the newline character, and similarly for \a, \t, and other sequences. The -E option switches to using extended regular expressions instead; it has been supported for years by GNU sed, and is now included in POSIX. BUGS top E-mail bug reports to bug-sed@gnu.org. Also, please include the output of ``sed --version'' in the body of your report if at all possible. AUTHOR top Written by Jay Fenlason, Tom Lord, Ken Pizzini, Paolo Bonzini, Jim Meyering, and Assaf Gordon. This sed program was built with SELinux support. SELinux is enabled on this system. GNU sed home page: <https://www.gnu.org/software/sed/>. General help using GNU software: <https://www.gnu.org/gethelp/>. E-mail bug reports to: <bug-sed@gnu.org>. COPYRIGHT top Copyright 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top awk(1), ed(1), grep(1), tr(1), perlre(1), sed.info, any of various books on sed, the sed FAQ (http://sed.sf.net/grabbag/tutorials/sedfaq.txt), http://sed.sf.net/grabbag/. The full documentation for sed is maintained as a Texinfo manual. If the info and sed programs are properly installed at your site, the command info sed should give you access to the complete manual. COLOPHON top This page is part of the sed (stream-oriented editor) project. Information about the project can be found at http://www.gnu.org/software/sed/. If you have a bug report for this manual page, send it to bug-sed@gnu.org. This page was obtained from the tarball sed-4.9.tar.gz fetched from https://www.gnu.org/software/sed/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU sed 4.9 November 2022 SED(1) Pages that refer to this page: gawk(1), grep(1), iostat2pcp(1), pmdaopenmetrics(1), pmlogrewrite(1), sheet2pcp(1), cpuset(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the directory "config" in the current folder and change directory to the first instance of the search Bash Command:<START>cd $(find . -name config -type d | sed 1q)<END>
search for the directory "ora10" in the entire file system
find / -type d -name "ora10"
['find']
Output a Bash command to accomplish the following task. Task: search for the directory "ora10" in the entire file system Bash Command:<START>find / -type d -name "ora10"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the directory "ora10" in the entire file system Bash Command:<START>find / -type d -name "ora10"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the directory "ora10" in the entire file system Bash Command:<START>find / -type d -name "ora10"<END>
search for the directory "uploads" in current folder and change the permission of the folder and all the files to 755
find . -type d -name 'uploads' -print0 | xargs -0 chmod -R 755
['find', 'xargs', 'chmod']
Output a Bash command to accomplish the following task. Task: search for the directory "uploads" in current folder and change the permission of the folder and all the files to 755 Bash Command:<START>find . -type d -name 'uploads' -print0 | xargs -0 chmod -R 755<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # chmod\n\n> Change the access permissions of a file or directory.\n> More information: <https://www.gnu.org/software/coreutils/chmod>.\n\n- Give the [u]ser who owns a file the right to e[x]ecute it:\n\n`chmod u+x {{path/to/file}}`\n\n- Give the [u]ser rights to [r]ead and [w]rite to a file/directory:\n\n`chmod u+rw {{path/to/file_or_directory}}`\n\n- Remove e[x]ecutable rights from the [g]roup:\n\n`chmod g-x {{path/to/file}}`\n\n- Give [a]ll users rights to [r]ead and e[x]ecute:\n\n`chmod a+rx {{path/to/file}}`\n\n- Give [o]thers (not in the file owner's group) the same rights as the [g]roup:\n\n`chmod o=g {{path/to/file}}`\n\n- Remove all rights from [o]thers:\n\n`chmod o= {{path/to/file}}`\n\n- Change permissions recursively giving [g]roup and [o]thers the ability to [w]rite:\n\n`chmod -R g+w,o+w {{path/to/directory}}`\n\n- Recursively give [a]ll users [r]ead permissions to files and e[X]ecute permissions to sub-directories within a directory:\n\n`chmod -R a+rX {{path/to/directory}}`\n Task: search for the directory "uploads" in current folder and change the permission of the folder and all the files to 755 Bash Command:<START>find . -type d -name 'uploads' -print0 | xargs -0 chmod -R 755<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. chmod(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training chmod(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | SETUID AND SETGID BITS | RESTRICTED DELETION FLAG OR STICKY BIT | OPTIONS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CHMOD(1) User Commands CHMOD(1) NAME top chmod - change file mode bits SYNOPSIS top chmod [OPTION]... MODE[,MODE]... FILE... chmod [OPTION]... OCTAL-MODE FILE... chmod [OPTION]... --reference=RFILE FILE... DESCRIPTION top This manual page documents the GNU version of chmod. chmod changes the file mode bits of each given file according to mode, which can be either a symbolic representation of changes to make, or an octal number representing the bit pattern for the new mode bits. The format of a symbolic mode is [ugoa...][[-+=][perms...]...], where perms is either zero or more letters from the set rwxXst, or a single letter from the set ugo. Multiple symbolic modes can be given, separated by commas. A combination of the letters ugoa controls which users' access to the file will be changed: the user who owns it (u), other users in the file's group (g), other users not in the file's group (o), or all users (a). If none of these are given, the effect is as if (a) were given, but bits that are set in the umask are not affected. The operator + causes the selected file mode bits to be added to the existing file mode bits of each file; - causes them to be removed; and = causes them to be added and causes unmentioned bits to be removed except that a directory's unmentioned set user and group ID bits are not affected. The letters rwxXst select file mode bits for the affected users: read (r), write (w), execute (or search for directories) (x), execute/search only if the file is a directory or already has execute permission for some user (X), set user or group ID on execution (s), restricted deletion flag or sticky bit (t). Instead of one or more of these letters, you can specify exactly one of the letters ugo: the permissions granted to the user who owns the file (u), the permissions granted to other users who are members of the file's group (g), and the permissions granted to users that are in neither of the two preceding categories (o). A numeric mode is from one to four octal digits (0-7), derived by adding up the bits with values 4, 2, and 1. Omitted digits are assumed to be leading zeros. The first digit selects the set user ID (4) and set group ID (2) and restricted deletion or sticky (1) attributes. The second digit selects permissions for the user who owns the file: read (4), write (2), and execute (1); the third selects permissions for other users in the file's group, with the same values; and the fourth for other users not in the file's group, with the same values. chmod never changes the permissions of symbolic links; the chmod system call cannot change their permissions. This is not a problem since the permissions of symbolic links are never used. However, for each symbolic link listed on the command line, chmod changes the permissions of the pointed-to file. In contrast, chmod ignores symbolic links encountered during recursive directory traversals. SETUID AND SETGID BITS top chmod clears the set-group-ID bit of a regular file if the file's group ID does not match the user's effective group ID or one of the user's supplementary group IDs, unless the user has appropriate privileges. Additional restrictions may cause the set-user-ID and set-group-ID bits of MODE or RFILE to be ignored. This behavior depends on the policy and functionality of the underlying chmod system call. When in doubt, check the underlying system behavior. For directories chmod preserves set-user-ID and set-group-ID bits unless you explicitly specify otherwise. You can set or clear the bits with symbolic modes like u+s and g-s. To clear these bits for directories with a numeric mode requires an additional leading zero like 00755, leading minus like -6000, or leading equals like =755. RESTRICTED DELETION FLAG OR STICKY BIT top The restricted deletion flag or sticky bit is a single bit, whose interpretation depends on the file type. For directories, it prevents unprivileged users from removing or renaming a file in the directory unless they own the file or the directory; this is called the restricted deletion flag for the directory, and is commonly found on world-writable directories like /tmp. For regular files on some older systems, the bit saves the program's text image on the swap device so it will load more quickly when run; this is called the sticky bit. OPTIONS top Change the mode of each FILE to MODE. With --reference, change the mode of each FILE to that of RFILE. -c, --changes like verbose but report only when a change is made -f, --silent, --quiet suppress most error messages -v, --verbose output a diagnostic for every file processed --no-preserve-root do not treat '/' specially (the default) --preserve-root fail to operate recursively on '/' --reference=RFILE use RFILE's mode instead of specifying MODE values. RFILE is always dereferenced if a symbolic link. -R, --recursive change files and directories recursively --help display this help and exit --version output version information and exit Each MODE is of the form '[ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=][0-7]+'. AUTHOR top Written by David MacKenzie and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top chmod(2) Full documentation <https://www.gnu.org/software/coreutils/chmod> or available locally via: info '(coreutils) chmod invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CHMOD(1) Pages that refer to this page: bash(1), chacl(1), find(1), nfs4_setfacl(1), rsync(1), setfacl(1), chmod(2), fcntl(2), lp(4), rsyncd.conf(5), path_resolution(7), symlink(7), xattr(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the directory "uploads" in current folder and change the permission of the folder and all the files to 755 Bash Command:<START>find . -type d -name 'uploads' -print0 | xargs -0 chmod -R 755<END>
search for the directory starting with "ora10" in the entire file system
find / -type d -name "ora10*"
['find']
Output a Bash command to accomplish the following task. Task: search for the directory starting with "ora10" in the entire file system Bash Command:<START>find / -type d -name "ora10*"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the directory starting with "ora10" in the entire file system Bash Command:<START>find / -type d -name "ora10*"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the directory starting with "ora10" in the entire file system Bash Command:<START>find / -type d -name "ora10*"<END>
search for the directory testdir in the folder /home
find /home -type d -name testdir
['find']
Output a Bash command to accomplish the following task. Task: search for the directory testdir in the folder /home Bash Command:<START>find /home -type d -name testdir<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the directory testdir in the folder /home Bash Command:<START>find /home -type d -name testdir<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the directory testdir in the folder /home Bash Command:<START>find /home -type d -name testdir<END>
search for the directory with the name aa in the current folder
find . -type d -name aa
['find']
Output a Bash command to accomplish the following task. Task: search for the directory with the name aa in the current folder Bash Command:<START>find . -type d -name aa<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the directory with the name aa in the current folder Bash Command:<START>find . -type d -name aa<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the directory with the name aa in the current folder Bash Command:<START>find . -type d -name aa<END>
search for the file ".user.log" in a folder
find /nfs/office -name .user.log -print
['find']
Output a Bash command to accomplish the following task. Task: search for the file ".user.log" in a folder Bash Command:<START>find /nfs/office -name .user.log -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file ".user.log" in a folder Bash Command:<START>find /nfs/office -name .user.log -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file ".user.log" in a folder Bash Command:<START>find /nfs/office -name .user.log -print<END>
search for the file "abc" in the current folder or display all the directories
find . -name abc -or -type d
['find']
Output a Bash command to accomplish the following task. Task: search for the file "abc" in the current folder or display all the directories Bash Command:<START>find . -name abc -or -type d<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file "abc" in the current folder or display all the directories Bash Command:<START>find . -name abc -or -type d<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file "abc" in the current folder or display all the directories Bash Command:<START>find . -name abc -or -type d<END>
search for the file "file" in current folder and save the output to the same file
find -name file -fprint file
['find', 'file']
Output a Bash command to accomplish the following task. Task: search for the file "file" in current folder and save the output to the same file Bash Command:<START>find -name file -fprint file<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # file\n\n> Determine file type.\n> More information: <https://manned.org/file>.\n\n- Give a description of the type of the specified file. Works fine for files with no file extension:\n\n`file {{path/to/file}}`\n\n- Look inside a zipped file and determine the file type(s) inside:\n\n`file -z {{foo.zip}}`\n\n- Allow file to work with special or device files:\n\n`file -s {{path/to/file}}`\n\n- Don't stop at first file type match; keep going until the end of the file:\n\n`file -k {{path/to/file}}`\n\n- Determine the MIME encoding type of a file:\n\n`file -i {{path/to/file}}`\n Task: search for the file "file" in current folder and save the output to the same file Bash Command:<START>find -name file -fprint file<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. file(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training file(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | ENVIRONMENT | FILES | EXIT STATUS | EXAMPLES | SEE ALSO | STANDARDS CONFORMANCE | SECURITY | MAGIC DIRECTORY | HISTORY | LEGAL NOTICE | BUGS | TODO | AVAILABILITY | COLOPHON FILE(1) General Commands Manual FILE(1) NAME top file determine file type SYNOPSIS top [-bcdEhiklLNnprsSvzZ0] [--apple] [--exclude-quiet] [--extension] [--mime-encoding] [--mime-type] [-e testname] [-F separator] [-f namefile] [-m magicfiles] [-P name=value] file ... -C [-m magicfiles] [--help] DESCRIPTION top This manual page documents version 5.45 of the command. tests each argument in an attempt to classify it. There are three sets of tests, performed in this order: filesystem tests, magic tests, and language tests. The first test that succeeds causes the file type to be printed. The type printed will usually contain one of the words text (the file contains only printing characters and a few common control characters and is probably safe to read on an ASCII terminal), executable (the file contains the result of compiling a program in a form understandable to some UNIX kernel or another), or data meaning anything else (data is usually binary or non- printable). Exceptions are well-known file formats (core files, tar archives) that are known to contain binary data. When modifying magic files or the program itself, make sure to preserve these keywords. Users depend on knowing that all the readable files in a directory have the word text printed. Don't do as Berkeley did and change shell commands text to shell script. The filesystem tests are based on examining the return from a stat(2) system call. The program checks to see if the file is empty, or if it's some sort of special file. Any known file types appropriate to the system you are running on (sockets, symbolic links, or named pipes (FIFOs) on those systems that implement them) are intuited if they are defined in the system header file <sys/stat.h>. The magic tests are used to check for files with data in particular fixed formats. The canonical example of this is a binary executable (compiled program) a.out file, whose format is defined in <elf.h>, <a.out.h> and possibly <exec.h> in the standard include directory. These files have a magic number stored in a particular place near the beginning of the file that tells the UNIX operating system that the file is a binary executable, and which of several types thereof. The concept of a magic number has been applied by extension to data files. Any file with some invariant identifier at a small fixed offset into the file can usually be described in this way. The information identifying these files is read from the compiled magic file /usr/local/share/misc/magic.mgc, or the files in the directory /usr/local/share/misc/magic if the compiled file does not exist. In addition, if $HOME/.magic.mgc or $HOME/.magic exists, it will be used in preference to the system magic files. If a file does not match any of the entries in the magic file, it is examined to see if it seems to be a text file. ASCII, ISO-8859-x, non-ISO 8-bit extended-ASCII character sets (such as those used on Macintosh and IBM PC systems), UTF-8-encoded Unicode, UTF-16-encoded Unicode, and EBCDIC character sets can be distinguished by the different ranges and sequences of bytes that constitute printable text in each set. If a file passes any of these tests, its character set is reported. ASCII, ISO-8859-x, UTF-8, and extended-ASCII files are identified as text because they will be mostly readable on nearly any terminal; UTF-16 and EBCDIC are only character data because, while they contain text, it is text that will require translation before it can be read. In addition, will attempt to determine other characteristics of text-type files. If the lines of a file are terminated by CR, CRLF, or NEL, instead of the Unix-standard LF, this will be reported. Files that contain embedded escape sequences or overstriking will also be identified. Once has determined the character set used in a text-type file, it will attempt to determine in what language the file is written. The language tests look for particular strings (cf. <names.h>) that can appear anywhere in the first few blocks of a file. For example, the keyword .br indicates that the file is most likely a troff(1) input file, just as the keyword struct indicates a C program. These tests are less reliable than the previous two groups, so they are performed last. The language test routines also test for some miscellany (such as tar(1) archives, JSON files). Any file that cannot be identified as having been written in any of the character sets listed above is simply said to be data. OPTIONS top --apple Causes the command to output the file type and creator code as used by older MacOS versions. The code consists of eight letters, the first describing the file type, the latter the creator. This option works properly only for file formats that have the apple-style output defined. -b, --brief Do not prepend filenames to output lines (brief mode). -C, --compile Write a magic.mgc output file that contains a pre-parsed version of the magic file or directory. -c, --checking-printout Cause a checking printout of the parsed form of the magic file. This is usually used in conjunction with the -m option to debug a new magic file before installing it. -d Prints internal debugging information to stderr. -E On filesystem errors (file not found etc), instead of handling the error as regular output as POSIX mandates and keep going, issue an error message and exit. -e, --exclude testname Exclude the test named in testname from the list of tests made to determine the file type. Valid test names are: apptype EMX application type (only on EMX). ascii Various types of text files (this test will try to guess the text encoding, irrespective of the setting of the encoding option). encoding Different text encodings for soft magic tests. tokens Ignored for backwards compatibility. cdf Prints details of Compound Document Files. compress Checks for, and looks inside, compressed files. csv Checks Comma Separated Value files. elf Prints ELF file details, provided soft magic tests are enabled and the elf magic is found. json Examines JSON (RFC-7159) files by parsing them for compliance. soft Consults magic files. simh Examines SIMH tape files. tar Examines tar files by verifying the checksum of the 512 byte tar header. Excluding this test can provide more detailed content description by using the soft magic method. text A synonym for ascii. --exclude-quiet Like --exclude but ignore tests that does not know about. This is intended for compatibility with older versions of . --extension Print a slash-separated list of valid extensions for the file type found. -F, --separator separator Use the specified string as the separator between the filename and the file result returned. Defaults to :. -f, --files-from namefile Read the names of the files to be examined from namefile (one per line) before the argument list. Either namefile or at least one filename argument must be present; to test the standard input, use - as a filename argument. Please note that namefile is unwrapped and the enclosed filenames are processed when this option is encountered and before any further options processing is done. This allows one to process multiple lists of files with different command line arguments on the same invocation. Thus if you want to set the delimiter, you need to do it before you specify the list of files, like: -F @ -f namefile, instead of: -f namefile -F @. -h, --no-dereference This option causes symlinks not to be followed (on systems that support symbolic links). This is the default if the environment variable POSIXLY_CORRECT is not defined. -i, --mime Causes the command to output mime type strings rather than the more traditional human readable ones. Thus it may say text/plain; charset=us-ascii rather than ASCII text. --mime-type, --mime-encoding Like -i, but print only the specified element(s). -k, --keep-going Don't stop at the first match, keep going. Subsequent matches will be have the string \012- prepended. (If you want a newline, see the -r option.) The magic pattern with the highest strength (see the -l option) comes first. -l, --list Shows a list of patterns and their strength sorted descending by magic(4) strength which is used for the matching (see also the -k option). -L, --dereference This option causes symlinks to be followed, as the like- named option in ls(1) (on systems that support symbolic links). This is the default if the environment variable POSIXLY_CORRECT is defined. -m, --magic-file magicfiles Specify an alternate list of files and directories containing magic. This can be a single item, or a colon- separated list. If a compiled magic file is found alongside a file or directory, it will be used instead. -N, --no-pad Don't pad filenames so that they align in the output. -n, --no-buffer Force stdout to be flushed after checking each file. This is only useful if checking a list of files. It is intended to be used by programs that want filetype output from a pipe. -p, --preserve-date On systems that support utime(3) or utimes(2), attempt to preserve the access time of files analyzed, to pretend that never read them. -P, --parameter name=value Set various parameter limits. Name Default Explanation bytes 1M max number of bytes to read from file elf_notes 256 max ELF notes processed elf_phnum 2K max ELF program sections processed elf_shnum 32K max ELF sections processed elf_shsize 128MB max ELF section size processed encoding 65K max number of bytes to determine encoding indir 50 recursion limit for indirect magic name 50 use count limit for name/use magic regex 8K length limit for regex searches -r, --raw Don't translate unprintable characters to \ooo. Normally translates unprintable characters to their octal representation. -s, --special-files Normally, only attempts to read and determine the type of argument files which stat(2) reports are ordinary files. This prevents problems, because reading special files may have peculiar consequences. Specifying the -s option causes to also read argument files which are block or character special files. This is useful for determining the filesystem types of the data in raw disk partitions, which are block special files. This option also causes to disregard the file size as reported by stat(2) since on some systems it reports a zero size for raw disk partitions. -S, --no-sandbox On systems where libseccomp (https://github.com/seccomp/libseccomp ) is available, the -S option disables sandboxing which is enabled by default. This option is needed for to execute external decompressing programs, i.e. when the -z option is specified and the built-in decompressors are not available. On systems where sandboxing is not available, this option has no effect. -v, --version Print the version of the program and exit. -z, --uncompress Try to look inside compressed files. -Z, --uncompress-noreport Try to look inside compressed files, but report information about the contents only not the compression. -0, --print0 Output a null character \0 after the end of the filename. Nice to cut(1) the output. This does not affect the separator, which is still printed. If this option is repeated more than once, then prints just the filename followed by a NUL followed by the description (or ERROR: text) followed by a second NUL for each entry. --help Print a help message and exit. ENVIRONMENT top The environment variable MAGIC can be used to set the default magic file name. If that variable is set, then will not attempt to open $HOME/.magic. adds .mgc to the value of this variable as appropriate. The environment variable POSIXLY_CORRECT controls (on systems that support symbolic links), whether will attempt to follow symlinks or not. If set, then follows symlink, otherwise it does not. This is also controlled by the -L and -h options. FILES top /usr/local/share/misc/magic.mgc Default compiled list of magic. /usr/local/share/misc/magic Directory containing default magic files. EXIT STATUS top will exit with 0 if the operation was successful or >0 if an error was encountered. The following errors cause diagnostic messages, but don't affect the program exit code (as POSIX requires), unless -E is specified: A file cannot be found There is no permission to read a file The file type cannot be determined EXAMPLES top $ file file.c file /dev/{wd0a,hda} file.c: C program text file: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), stripped /dev/wd0a: block special (0/0) /dev/hda: block special (3/0) $ file -s /dev/wd0{b,d} /dev/wd0b: data /dev/wd0d: x86 boot sector $ file -s /dev/hda{,1,2,3,4,5,6,7,8,9,10} /dev/hda: x86 boot sector /dev/hda1: Linux/i386 ext2 filesystem /dev/hda2: x86 boot sector /dev/hda3: x86 boot sector, extended partition table /dev/hda4: Linux/i386 ext2 filesystem /dev/hda5: Linux/i386 swap file /dev/hda6: Linux/i386 swap file /dev/hda7: Linux/i386 swap file /dev/hda8: Linux/i386 swap file /dev/hda9: empty /dev/hda10: empty $ file -i file.c file /dev/{wd0a,hda} file.c: text/x-c file: application/x-executable /dev/hda: application/x-not-regular-file /dev/wd0a: application/x-not-regular-file SEE ALSO top hexdump(1), od(1), strings(1), magic(4) STANDARDS CONFORMANCE top This program is believed to exceed the System V Interface Definition of FILE(CMD), as near as one can determine from the vague language contained therein. Its behavior is mostly compatible with the System V program of the same name. This version knows more magic, however, so it will produce different (albeit more accurate) output in many cases. The one significant difference between this version and System V is that this version treats any white space as a delimiter, so that spaces in pattern strings must be escaped. For example, >10 string language impress (imPRESS data) in an existing magic file would have to be changed to >10 string language\ impress (imPRESS data) In addition, in this version, if a pattern string contains a backslash, it must be escaped. For example 0 string \begindata Andrew Toolkit document in an existing magic file would have to be changed to 0 string \\begindata Andrew Toolkit document SunOS releases 3.2 and later from Sun Microsystems include a command derived from the System V one, but with some extensions. This version differs from Sun's only in minor ways. It includes the extension of the & operator, used as, for example, >16 long&0x7fffffff >0 not stripped SECURITY top On systems where libseccomp (https://github.com/seccomp/libseccomp ) is available, is enforces limiting system calls to only the ones necessary for the operation of the program. This enforcement does not provide any security benefit when is asked to decompress input files running external programs with the -z option. To enable execution of external decompressors, one needs to disable sandboxing using the -S option. MAGIC DIRECTORY top The magic file entries have been collected from various sources, mainly USENET, and contributed by various authors. Christos Zoulas (address below) will collect additional or corrected magic file entries. A consolidation of magic file entries will be distributed periodically. The order of entries in the magic file is significant. Depending on what system you are using, the order that they are put together may be incorrect. If your old command uses a magic file, keep the old magic file around for comparison purposes (rename it to /usr/local/share/misc/magic.orig). HISTORY top There has been a command in every UNIX since at least Research Version 4 (man page dated November, 1973). The System V version introduced one significant major change: the external list of magic types. This slowed the program down slightly but made it a lot more flexible. This program, based on the System V version, was written by Ian Darwin ian@darwinsys.com without looking at anybody else's source code. John Gilmore revised the code extensively, making it better than the first version. Geoff Collyer found several inadequacies and provided some magic file entries. Contributions of the & operator by Rob McMahon, cudcv@warwick.ac.uk, 1989. Guy Harris, guy@netapp.com, made many changes from 1993 to the present. Primary development and maintenance from 1990 to the present by Christos Zoulas christos@astron.com. Altered by Chris Lowth chris@lowth.com, 2000: handle the -i option to output mime type strings, using an alternative magic file and internal logic. Altered by Eric Fischer enf@pobox.com, July, 2000, to identify character codes and attempt to identify the languages of non- ASCII files. Altered by Reuben Thomas rrt@sc3d.org, 2007-2011, to improve MIME support, merge MIME and non-MIME magic, support directories as well as files of magic, apply many bug fixes, update and fix a lot of magic, improve the build system, improve the documentation, and rewrite the Python bindings in pure Python. The list of contributors to the magic directory (magic files) is too long to include here. You know who you are; thank you. Many contributors are listed in the source files. LEGAL NOTICE top Copyright (c) Ian F. Darwin, Toronto, Canada, 1986-1999. Covered by the standard Berkeley Software Distribution copyright; see the file COPYING in the source distribution. The files tar.h and is_tar.c were written by John Gilmore from his public-domain tar(1) program, and are not covered by the above license. BUGS top Please report bugs and send patches to the bug tracker at https://bugs.astron.com/ or the mailing list at file@astron.com (visit https://mailman.astron.com/mailman/listinfo/file first to subscribe). TODO top Fix output so that tests for MIME and APPLE flags are not needed all over the place, and actual output is only done in one place. This needs a design. Suggestion: push possible outputs on to a list, then pick the last-pushed (most specific, one hopes) value at the end, or use a default if the list is empty. This should not slow down evaluation. The handling of MAGIC_CONTINUE and printing \012- between entries is clumsy and complicated; refactor and centralize. Some of the encoding logic is hard-coded in encoding.c and can be moved to the magic files if we had a !:charset annotation. Continue to squash all magic bugs. See Debian BTS for a good source. Store arbitrarily long strings, for example for %s patterns, so that they can be printed out. Fixes Debian bug #271672. This can be done by allocating strings in a string pool, storing the string pool at the end of the magic file and converting all the string pointers to relative offsets from the string pool. Add syntax for relative offsets after current level (Debian bug #466037). Make file -ki work, i.e. give multiple MIME types. Add a zip library so we can peek inside Office2007 documents to print more details about their contents. Add an option to print URLs for the sources of the file descriptions. Combine script searches and add a way to map executable names to MIME types (e.g. have a magic value for !:mime which causes the resulting string to be looked up in a table). This would avoid adding the same magic repeatedly for each new hash-bang interpreter. When a file descriptor is available, we can skip and adjust the buffer instead of the hacky buffer management we do now. Fix name and use to check for consistency at compile time (duplicate name, use pointing to undefined name ). Make name / use more efficient by keeping a sorted list of names. Special-case ^ to flip endianness in the parser so that it does not have to be escaped, and document it. If the offsets specified internally in the file exceed the buffer size ( HOWMANY variable in file.h), then we don't seek to that offset, but we give up. It would be better if buffer managements was done when the file descriptor is available so we can seek around the file. One must be careful though because this has performance and thus security considerations, because one can slow down things by repeatedly seeking. There is support now for keeping separate buffers and having offsets from the end of the file, but the internal buffer management still needs an overhaul. AVAILABILITY top You can obtain the original author's latest version by anonymous FTP on ftp.astron.com in the directory /pub/file/file-X.YZ.tar.gz. COLOPHON top This page is part of the file (a file type guesser) project. Information about the project can be found at http://www.darwinsys.com/file/. If you have a bug report for this manual page, see http://bugs.gw.com/my_view_page.php. This page was obtained from the project's upstream Git read-only mirror of the CVS repository https://github.com/glensc/file on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-12-21.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU May 21, 2023 FILE(1) Pages that refer to this page: dh_installmanpages(1), dh_strip(1), ippeveprinter(1), pmcd(1), scr_dump(5), term(5), suffixes(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file "file" in current folder and save the output to the same file Bash Command:<START>find -name file -fprint file<END>
search for the file "file" in the current folder excluding those in the sub directory ".git"
find . -path ./.git -prune -o -name file -print
['find', 'file']
Output a Bash command to accomplish the following task. Task: search for the file "file" in the current folder excluding those in the sub directory ".git" Bash Command:<START>find . -path ./.git -prune -o -name file -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # file\n\n> Determine file type.\n> More information: <https://manned.org/file>.\n\n- Give a description of the type of the specified file. Works fine for files with no file extension:\n\n`file {{path/to/file}}`\n\n- Look inside a zipped file and determine the file type(s) inside:\n\n`file -z {{foo.zip}}`\n\n- Allow file to work with special or device files:\n\n`file -s {{path/to/file}}`\n\n- Don't stop at first file type match; keep going until the end of the file:\n\n`file -k {{path/to/file}}`\n\n- Determine the MIME encoding type of a file:\n\n`file -i {{path/to/file}}`\n Task: search for the file "file" in the current folder excluding those in the sub directory ".git" Bash Command:<START>find . -path ./.git -prune -o -name file -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. file(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training file(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | ENVIRONMENT | FILES | EXIT STATUS | EXAMPLES | SEE ALSO | STANDARDS CONFORMANCE | SECURITY | MAGIC DIRECTORY | HISTORY | LEGAL NOTICE | BUGS | TODO | AVAILABILITY | COLOPHON FILE(1) General Commands Manual FILE(1) NAME top file determine file type SYNOPSIS top [-bcdEhiklLNnprsSvzZ0] [--apple] [--exclude-quiet] [--extension] [--mime-encoding] [--mime-type] [-e testname] [-F separator] [-f namefile] [-m magicfiles] [-P name=value] file ... -C [-m magicfiles] [--help] DESCRIPTION top This manual page documents version 5.45 of the command. tests each argument in an attempt to classify it. There are three sets of tests, performed in this order: filesystem tests, magic tests, and language tests. The first test that succeeds causes the file type to be printed. The type printed will usually contain one of the words text (the file contains only printing characters and a few common control characters and is probably safe to read on an ASCII terminal), executable (the file contains the result of compiling a program in a form understandable to some UNIX kernel or another), or data meaning anything else (data is usually binary or non- printable). Exceptions are well-known file formats (core files, tar archives) that are known to contain binary data. When modifying magic files or the program itself, make sure to preserve these keywords. Users depend on knowing that all the readable files in a directory have the word text printed. Don't do as Berkeley did and change shell commands text to shell script. The filesystem tests are based on examining the return from a stat(2) system call. The program checks to see if the file is empty, or if it's some sort of special file. Any known file types appropriate to the system you are running on (sockets, symbolic links, or named pipes (FIFOs) on those systems that implement them) are intuited if they are defined in the system header file <sys/stat.h>. The magic tests are used to check for files with data in particular fixed formats. The canonical example of this is a binary executable (compiled program) a.out file, whose format is defined in <elf.h>, <a.out.h> and possibly <exec.h> in the standard include directory. These files have a magic number stored in a particular place near the beginning of the file that tells the UNIX operating system that the file is a binary executable, and which of several types thereof. The concept of a magic number has been applied by extension to data files. Any file with some invariant identifier at a small fixed offset into the file can usually be described in this way. The information identifying these files is read from the compiled magic file /usr/local/share/misc/magic.mgc, or the files in the directory /usr/local/share/misc/magic if the compiled file does not exist. In addition, if $HOME/.magic.mgc or $HOME/.magic exists, it will be used in preference to the system magic files. If a file does not match any of the entries in the magic file, it is examined to see if it seems to be a text file. ASCII, ISO-8859-x, non-ISO 8-bit extended-ASCII character sets (such as those used on Macintosh and IBM PC systems), UTF-8-encoded Unicode, UTF-16-encoded Unicode, and EBCDIC character sets can be distinguished by the different ranges and sequences of bytes that constitute printable text in each set. If a file passes any of these tests, its character set is reported. ASCII, ISO-8859-x, UTF-8, and extended-ASCII files are identified as text because they will be mostly readable on nearly any terminal; UTF-16 and EBCDIC are only character data because, while they contain text, it is text that will require translation before it can be read. In addition, will attempt to determine other characteristics of text-type files. If the lines of a file are terminated by CR, CRLF, or NEL, instead of the Unix-standard LF, this will be reported. Files that contain embedded escape sequences or overstriking will also be identified. Once has determined the character set used in a text-type file, it will attempt to determine in what language the file is written. The language tests look for particular strings (cf. <names.h>) that can appear anywhere in the first few blocks of a file. For example, the keyword .br indicates that the file is most likely a troff(1) input file, just as the keyword struct indicates a C program. These tests are less reliable than the previous two groups, so they are performed last. The language test routines also test for some miscellany (such as tar(1) archives, JSON files). Any file that cannot be identified as having been written in any of the character sets listed above is simply said to be data. OPTIONS top --apple Causes the command to output the file type and creator code as used by older MacOS versions. The code consists of eight letters, the first describing the file type, the latter the creator. This option works properly only for file formats that have the apple-style output defined. -b, --brief Do not prepend filenames to output lines (brief mode). -C, --compile Write a magic.mgc output file that contains a pre-parsed version of the magic file or directory. -c, --checking-printout Cause a checking printout of the parsed form of the magic file. This is usually used in conjunction with the -m option to debug a new magic file before installing it. -d Prints internal debugging information to stderr. -E On filesystem errors (file not found etc), instead of handling the error as regular output as POSIX mandates and keep going, issue an error message and exit. -e, --exclude testname Exclude the test named in testname from the list of tests made to determine the file type. Valid test names are: apptype EMX application type (only on EMX). ascii Various types of text files (this test will try to guess the text encoding, irrespective of the setting of the encoding option). encoding Different text encodings for soft magic tests. tokens Ignored for backwards compatibility. cdf Prints details of Compound Document Files. compress Checks for, and looks inside, compressed files. csv Checks Comma Separated Value files. elf Prints ELF file details, provided soft magic tests are enabled and the elf magic is found. json Examines JSON (RFC-7159) files by parsing them for compliance. soft Consults magic files. simh Examines SIMH tape files. tar Examines tar files by verifying the checksum of the 512 byte tar header. Excluding this test can provide more detailed content description by using the soft magic method. text A synonym for ascii. --exclude-quiet Like --exclude but ignore tests that does not know about. This is intended for compatibility with older versions of . --extension Print a slash-separated list of valid extensions for the file type found. -F, --separator separator Use the specified string as the separator between the filename and the file result returned. Defaults to :. -f, --files-from namefile Read the names of the files to be examined from namefile (one per line) before the argument list. Either namefile or at least one filename argument must be present; to test the standard input, use - as a filename argument. Please note that namefile is unwrapped and the enclosed filenames are processed when this option is encountered and before any further options processing is done. This allows one to process multiple lists of files with different command line arguments on the same invocation. Thus if you want to set the delimiter, you need to do it before you specify the list of files, like: -F @ -f namefile, instead of: -f namefile -F @. -h, --no-dereference This option causes symlinks not to be followed (on systems that support symbolic links). This is the default if the environment variable POSIXLY_CORRECT is not defined. -i, --mime Causes the command to output mime type strings rather than the more traditional human readable ones. Thus it may say text/plain; charset=us-ascii rather than ASCII text. --mime-type, --mime-encoding Like -i, but print only the specified element(s). -k, --keep-going Don't stop at the first match, keep going. Subsequent matches will be have the string \012- prepended. (If you want a newline, see the -r option.) The magic pattern with the highest strength (see the -l option) comes first. -l, --list Shows a list of patterns and their strength sorted descending by magic(4) strength which is used for the matching (see also the -k option). -L, --dereference This option causes symlinks to be followed, as the like- named option in ls(1) (on systems that support symbolic links). This is the default if the environment variable POSIXLY_CORRECT is defined. -m, --magic-file magicfiles Specify an alternate list of files and directories containing magic. This can be a single item, or a colon- separated list. If a compiled magic file is found alongside a file or directory, it will be used instead. -N, --no-pad Don't pad filenames so that they align in the output. -n, --no-buffer Force stdout to be flushed after checking each file. This is only useful if checking a list of files. It is intended to be used by programs that want filetype output from a pipe. -p, --preserve-date On systems that support utime(3) or utimes(2), attempt to preserve the access time of files analyzed, to pretend that never read them. -P, --parameter name=value Set various parameter limits. Name Default Explanation bytes 1M max number of bytes to read from file elf_notes 256 max ELF notes processed elf_phnum 2K max ELF program sections processed elf_shnum 32K max ELF sections processed elf_shsize 128MB max ELF section size processed encoding 65K max number of bytes to determine encoding indir 50 recursion limit for indirect magic name 50 use count limit for name/use magic regex 8K length limit for regex searches -r, --raw Don't translate unprintable characters to \ooo. Normally translates unprintable characters to their octal representation. -s, --special-files Normally, only attempts to read and determine the type of argument files which stat(2) reports are ordinary files. This prevents problems, because reading special files may have peculiar consequences. Specifying the -s option causes to also read argument files which are block or character special files. This is useful for determining the filesystem types of the data in raw disk partitions, which are block special files. This option also causes to disregard the file size as reported by stat(2) since on some systems it reports a zero size for raw disk partitions. -S, --no-sandbox On systems where libseccomp (https://github.com/seccomp/libseccomp ) is available, the -S option disables sandboxing which is enabled by default. This option is needed for to execute external decompressing programs, i.e. when the -z option is specified and the built-in decompressors are not available. On systems where sandboxing is not available, this option has no effect. -v, --version Print the version of the program and exit. -z, --uncompress Try to look inside compressed files. -Z, --uncompress-noreport Try to look inside compressed files, but report information about the contents only not the compression. -0, --print0 Output a null character \0 after the end of the filename. Nice to cut(1) the output. This does not affect the separator, which is still printed. If this option is repeated more than once, then prints just the filename followed by a NUL followed by the description (or ERROR: text) followed by a second NUL for each entry. --help Print a help message and exit. ENVIRONMENT top The environment variable MAGIC can be used to set the default magic file name. If that variable is set, then will not attempt to open $HOME/.magic. adds .mgc to the value of this variable as appropriate. The environment variable POSIXLY_CORRECT controls (on systems that support symbolic links), whether will attempt to follow symlinks or not. If set, then follows symlink, otherwise it does not. This is also controlled by the -L and -h options. FILES top /usr/local/share/misc/magic.mgc Default compiled list of magic. /usr/local/share/misc/magic Directory containing default magic files. EXIT STATUS top will exit with 0 if the operation was successful or >0 if an error was encountered. The following errors cause diagnostic messages, but don't affect the program exit code (as POSIX requires), unless -E is specified: A file cannot be found There is no permission to read a file The file type cannot be determined EXAMPLES top $ file file.c file /dev/{wd0a,hda} file.c: C program text file: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), stripped /dev/wd0a: block special (0/0) /dev/hda: block special (3/0) $ file -s /dev/wd0{b,d} /dev/wd0b: data /dev/wd0d: x86 boot sector $ file -s /dev/hda{,1,2,3,4,5,6,7,8,9,10} /dev/hda: x86 boot sector /dev/hda1: Linux/i386 ext2 filesystem /dev/hda2: x86 boot sector /dev/hda3: x86 boot sector, extended partition table /dev/hda4: Linux/i386 ext2 filesystem /dev/hda5: Linux/i386 swap file /dev/hda6: Linux/i386 swap file /dev/hda7: Linux/i386 swap file /dev/hda8: Linux/i386 swap file /dev/hda9: empty /dev/hda10: empty $ file -i file.c file /dev/{wd0a,hda} file.c: text/x-c file: application/x-executable /dev/hda: application/x-not-regular-file /dev/wd0a: application/x-not-regular-file SEE ALSO top hexdump(1), od(1), strings(1), magic(4) STANDARDS CONFORMANCE top This program is believed to exceed the System V Interface Definition of FILE(CMD), as near as one can determine from the vague language contained therein. Its behavior is mostly compatible with the System V program of the same name. This version knows more magic, however, so it will produce different (albeit more accurate) output in many cases. The one significant difference between this version and System V is that this version treats any white space as a delimiter, so that spaces in pattern strings must be escaped. For example, >10 string language impress (imPRESS data) in an existing magic file would have to be changed to >10 string language\ impress (imPRESS data) In addition, in this version, if a pattern string contains a backslash, it must be escaped. For example 0 string \begindata Andrew Toolkit document in an existing magic file would have to be changed to 0 string \\begindata Andrew Toolkit document SunOS releases 3.2 and later from Sun Microsystems include a command derived from the System V one, but with some extensions. This version differs from Sun's only in minor ways. It includes the extension of the & operator, used as, for example, >16 long&0x7fffffff >0 not stripped SECURITY top On systems where libseccomp (https://github.com/seccomp/libseccomp ) is available, is enforces limiting system calls to only the ones necessary for the operation of the program. This enforcement does not provide any security benefit when is asked to decompress input files running external programs with the -z option. To enable execution of external decompressors, one needs to disable sandboxing using the -S option. MAGIC DIRECTORY top The magic file entries have been collected from various sources, mainly USENET, and contributed by various authors. Christos Zoulas (address below) will collect additional or corrected magic file entries. A consolidation of magic file entries will be distributed periodically. The order of entries in the magic file is significant. Depending on what system you are using, the order that they are put together may be incorrect. If your old command uses a magic file, keep the old magic file around for comparison purposes (rename it to /usr/local/share/misc/magic.orig). HISTORY top There has been a command in every UNIX since at least Research Version 4 (man page dated November, 1973). The System V version introduced one significant major change: the external list of magic types. This slowed the program down slightly but made it a lot more flexible. This program, based on the System V version, was written by Ian Darwin ian@darwinsys.com without looking at anybody else's source code. John Gilmore revised the code extensively, making it better than the first version. Geoff Collyer found several inadequacies and provided some magic file entries. Contributions of the & operator by Rob McMahon, cudcv@warwick.ac.uk, 1989. Guy Harris, guy@netapp.com, made many changes from 1993 to the present. Primary development and maintenance from 1990 to the present by Christos Zoulas christos@astron.com. Altered by Chris Lowth chris@lowth.com, 2000: handle the -i option to output mime type strings, using an alternative magic file and internal logic. Altered by Eric Fischer enf@pobox.com, July, 2000, to identify character codes and attempt to identify the languages of non- ASCII files. Altered by Reuben Thomas rrt@sc3d.org, 2007-2011, to improve MIME support, merge MIME and non-MIME magic, support directories as well as files of magic, apply many bug fixes, update and fix a lot of magic, improve the build system, improve the documentation, and rewrite the Python bindings in pure Python. The list of contributors to the magic directory (magic files) is too long to include here. You know who you are; thank you. Many contributors are listed in the source files. LEGAL NOTICE top Copyright (c) Ian F. Darwin, Toronto, Canada, 1986-1999. Covered by the standard Berkeley Software Distribution copyright; see the file COPYING in the source distribution. The files tar.h and is_tar.c were written by John Gilmore from his public-domain tar(1) program, and are not covered by the above license. BUGS top Please report bugs and send patches to the bug tracker at https://bugs.astron.com/ or the mailing list at file@astron.com (visit https://mailman.astron.com/mailman/listinfo/file first to subscribe). TODO top Fix output so that tests for MIME and APPLE flags are not needed all over the place, and actual output is only done in one place. This needs a design. Suggestion: push possible outputs on to a list, then pick the last-pushed (most specific, one hopes) value at the end, or use a default if the list is empty. This should not slow down evaluation. The handling of MAGIC_CONTINUE and printing \012- between entries is clumsy and complicated; refactor and centralize. Some of the encoding logic is hard-coded in encoding.c and can be moved to the magic files if we had a !:charset annotation. Continue to squash all magic bugs. See Debian BTS for a good source. Store arbitrarily long strings, for example for %s patterns, so that they can be printed out. Fixes Debian bug #271672. This can be done by allocating strings in a string pool, storing the string pool at the end of the magic file and converting all the string pointers to relative offsets from the string pool. Add syntax for relative offsets after current level (Debian bug #466037). Make file -ki work, i.e. give multiple MIME types. Add a zip library so we can peek inside Office2007 documents to print more details about their contents. Add an option to print URLs for the sources of the file descriptions. Combine script searches and add a way to map executable names to MIME types (e.g. have a magic value for !:mime which causes the resulting string to be looked up in a table). This would avoid adding the same magic repeatedly for each new hash-bang interpreter. When a file descriptor is available, we can skip and adjust the buffer instead of the hacky buffer management we do now. Fix name and use to check for consistency at compile time (duplicate name, use pointing to undefined name ). Make name / use more efficient by keeping a sorted list of names. Special-case ^ to flip endianness in the parser so that it does not have to be escaped, and document it. If the offsets specified internally in the file exceed the buffer size ( HOWMANY variable in file.h), then we don't seek to that offset, but we give up. It would be better if buffer managements was done when the file descriptor is available so we can seek around the file. One must be careful though because this has performance and thus security considerations, because one can slow down things by repeatedly seeking. There is support now for keeping separate buffers and having offsets from the end of the file, but the internal buffer management still needs an overhaul. AVAILABILITY top You can obtain the original author's latest version by anonymous FTP on ftp.astron.com in the directory /pub/file/file-X.YZ.tar.gz. COLOPHON top This page is part of the file (a file type guesser) project. Information about the project can be found at http://www.darwinsys.com/file/. If you have a bug report for this manual page, see http://bugs.gw.com/my_view_page.php. This page was obtained from the project's upstream Git read-only mirror of the CVS repository https://github.com/glensc/file on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-12-21.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU May 21, 2023 FILE(1) Pages that refer to this page: dh_installmanpages(1), dh_strip(1), ippeveprinter(1), pmcd(1), scr_dump(5), term(5), suffixes(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file "file" in the current folder excluding those in the sub directory ".git" Bash Command:<START>find . -path ./.git -prune -o -name file -print<END>
search for the file "file1" in the entire file system
find / -name file1
['find']
Output a Bash command to accomplish the following task. Task: search for the file "file1" in the entire file system Bash Command:<START>find / -name file1<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file "file1" in the entire file system Bash Command:<START>find / -name file1<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file "file1" in the entire file system Bash Command:<START>find / -name file1<END>
search for the file "file_name" in the folder /path
find /path -name file_name
['find']
Output a Bash command to accomplish the following task. Task: search for the file "file_name" in the folder /path Bash Command:<START>find /path -name file_name<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file "file_name" in the folder /path Bash Command:<START>find /path -name file_name<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file "file_name" in the folder /path Bash Command:<START>find /path -name file_name<END>
search for the file "filename" in the entire file system
find / -name filename
['find']
Output a Bash command to accomplish the following task. Task: search for the file "filename" in the entire file system Bash Command:<START>find / -name filename<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file "filename" in the entire file system Bash Command:<START>find / -name filename<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file "filename" in the entire file system Bash Command:<START>find / -name filename<END>
search for the file "foo.txt" in the entire file system
find / -name foo.txt
['find']
Output a Bash command to accomplish the following task. Task: search for the file "foo.txt" in the entire file system Bash Command:<START>find / -name foo.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file "foo.txt" in the entire file system Bash Command:<START>find / -name foo.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file "foo.txt" in the entire file system Bash Command:<START>find / -name foo.txt<END>
search for the file "foobar.txt" in the folder "/home/mywebsite"
find /home/mywebsite -type f -name "foobar.txt"
['find']
Output a Bash command to accomplish the following task. Task: search for the file "foobar.txt" in the folder "/home/mywebsite" Bash Command:<START>find /home/mywebsite -type f -name "foobar.txt"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file "foobar.txt" in the folder "/home/mywebsite" Bash Command:<START>find /home/mywebsite -type f -name "foobar.txt"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file "foobar.txt" in the folder "/home/mywebsite" Bash Command:<START>find /home/mywebsite -type f -name "foobar.txt"<END>
search for the file "job.history" in the folder /data/Spoolln and search for multiple patterns in the file and display the count of matched lines along with the pattern
find /data/SpoolIn -name job.history | xargs grep -o -m 1 -h 'FAIL\|ABOR' | sort | uniq -c
['find', 'xargs', 'grep', 'sort', 'uniq']
Output a Bash command to accomplish the following task. Task: search for the file "job.history" in the folder /data/Spoolln and search for multiple patterns in the file and display the count of matched lines along with the pattern Bash Command:<START>find /data/SpoolIn -name job.history | xargs grep -o -m 1 -h 'FAIL\|ABOR' | sort | uniq -c<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n # sort\n\n> Sort lines of text files.\n> More information: <https://www.gnu.org/software/coreutils/sort>.\n\n- Sort a file in ascending order:\n\n`sort {{path/to/file}}`\n\n- Sort a file in descending order:\n\n`sort --reverse {{path/to/file}}`\n\n- Sort a file in case-insensitive way:\n\n`sort --ignore-case {{path/to/file}}`\n\n- Sort a file using numeric rather than alphabetic order:\n\n`sort --numeric-sort {{path/to/file}}`\n\n- Sort `/etc/passwd` by the 3rd field of each line numerically, using ":" as a field separator:\n\n`sort --field-separator={{:}} --key={{3n}} {{/etc/passwd}}`\n\n- Sort a file preserving only unique lines:\n\n`sort --unique {{path/to/file}}`\n\n- Sort a file, printing the output to the specified output file (can be used to sort a file in-place):\n\n`sort --output={{path/to/file}} {{path/to/file}}`\n\n- Sort numbers with exponents:\n\n`sort --general-numeric-sort {{path/to/file}}`\n # uniq\n\n> Output the unique lines from a input or file.\n> Since it does not detect repeated lines unless they are adjacent, we need to sort them first.\n> More information: <https://www.gnu.org/software/coreutils/uniq>.\n\n- Display each line once:\n\n`sort {{path/to/file}} | uniq`\n\n- Display only unique lines:\n\n`sort {{path/to/file}} | uniq -u`\n\n- Display only duplicate lines:\n\n`sort {{path/to/file}} | uniq -d`\n\n- Display number of occurrences of each line along with that line:\n\n`sort {{path/to/file}} | uniq -c`\n\n- Display number of occurrences of each line, sorted by the most frequent:\n\n`sort {{path/to/file}} | uniq -c | sort -nr`\n Task: search for the file "job.history" in the folder /data/Spoolln and search for multiple patterns in the file and display the count of matched lines along with the pattern Bash Command:<START>find /data/SpoolIn -name job.history | xargs grep -o -m 1 -h 'FAIL\|ABOR' | sort | uniq -c<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. sort(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training sort(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON SORT(1) User Commands SORT(1) NAME top sort - sort lines of text files SYNOPSIS top sort [OPTION]... [FILE]... sort [OPTION]... --files0-from=F DESCRIPTION top Write sorted concatenation of all FILE(s) to standard output. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. Ordering options: -b, --ignore-leading-blanks ignore leading blanks -d, --dictionary-order consider only blanks and alphanumeric characters -f, --ignore-case fold lower case to upper case characters -g, --general-numeric-sort compare according to general numerical value -i, --ignore-nonprinting consider only printable characters -M, --month-sort compare (unknown) < 'JAN' < ... < 'DEC' -h, --human-numeric-sort compare human readable numbers (e.g., 2K 1G) -n, --numeric-sort compare according to string numerical value -R, --random-sort shuffle, but group identical keys. See shuf(1) --random-source=FILE get random bytes from FILE -r, --reverse reverse the result of comparisons --sort=WORD sort according to WORD: general-numeric -g, human-numeric -h, month -M, numeric -n, random -R, version -V -V, --version-sort natural sort of (version) numbers within text Other options: --batch-size=NMERGE merge at most NMERGE inputs at once; for more use temp files -c, --check, --check=diagnose-first check for sorted input; do not sort -C, --check=quiet, --check=silent like -c, but do not report first bad line --compress-program=PROG compress temporaries with PROG; decompress them with PROG -d --debug annotate the part of the line used to sort, and warn about questionable usage to stderr --files0-from=F read input from the files specified by NUL-terminated names in file F; If F is - then read names from standard input -k, --key=KEYDEF sort via a key; KEYDEF gives location and type -m, --merge merge already sorted files; do not sort -o, --output=FILE write result to FILE instead of standard output -s, --stable stabilize sort by disabling last-resort comparison -S, --buffer-size=SIZE use SIZE for main memory buffer -t, --field-separator=SEP use SEP instead of non-blank to blank transition -T, --temporary-directory=DIR use DIR for temporaries, not $TMPDIR or /tmp; multiple options specify multiple directories --parallel=N change the number of sorts run concurrently to N -u, --unique with -c, check for strict ordering; without -c, output only the first of an equal run -z, --zero-terminated line delimiter is NUL, not newline --help display this help and exit --version output version information and exit KEYDEF is F[.C][OPTS][,F[.C][OPTS]] for start and stop position, where F is a field number and C a character position in the field; both are origin 1, and the stop position defaults to the line's end. If neither -t nor -b is in effect, characters in a field are counted from the beginning of the preceding whitespace. OPTS is one or more single-letter ordering options [bdfgiMhnRrV], which override global ordering options for that key. If no key is given, use the entire line as the key. Use --debug to diagnose incorrect key usage. SIZE may be followed by the following multiplicative suffixes: % 1% of memory, b 1, K 1024 (default), and so on for M, G, T, P, E, Z, Y, R, Q. *** WARNING *** The locale specified by the environment affects sort order. Set LC_ALL=C to get the traditional sort order that uses native byte values. AUTHOR top Written by Mike Haertel and Paul Eggert. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top shuf(1), uniq(1) Full documentation <https://www.gnu.org/software/coreutils/sort> or available locally via: info '(coreutils) sort invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 SORT(1) Pages that refer to this page: column(1), grep(1), look(1), prlimit(1), ps(1), uniq(1), qsort(3), environ(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. uniq(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training uniq(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON UNIQ(1) User Commands UNIQ(1) NAME top uniq - report or omit repeated lines SYNOPSIS top uniq [OPTION]... [INPUT [OUTPUT]] DESCRIPTION top Filter adjacent matching lines from INPUT (or standard input), writing to OUTPUT (or standard output). With no options, matching lines are merged to the first occurrence. Mandatory arguments to long options are mandatory for short options too. -c, --count prefix lines by the number of occurrences -d, --repeated only print duplicate lines, one for each group -D print all duplicate lines --all-repeated[=METHOD] like -D, but allow separating groups with an empty line; METHOD={none(default),prepend,separate} -f, --skip-fields=N avoid comparing the first N fields --group[=METHOD] show all items, separating groups with an empty line; METHOD={separate(default),prepend,append,both} -i, --ignore-case ignore differences in case when comparing -s, --skip-chars=N avoid comparing the first N characters -u, --unique only print unique lines -z, --zero-terminated line delimiter is NUL, not newline -w, --check-chars=N compare no more than N characters in lines --help display this help and exit --version output version information and exit A field is a run of blanks (usually spaces and/or TABs), then non-blank characters. Fields are skipped before chars. Note: 'uniq' does not detect repeated lines unless they are adjacent. You may want to sort the input first, or use 'sort -u' without 'uniq'. AUTHOR top Written by Richard M. Stallman and David MacKenzie. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top comm(1), join(1), sort(1) Full documentation <https://www.gnu.org/software/coreutils/uniq> or available locally via: info '(coreutils) uniq invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 UNIQ(1) Pages that refer to this page: comm(1), join(1), sort(1) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file "job.history" in the folder /data/Spoolln and search for multiple patterns in the file and display the count of matched lines along with the pattern Bash Command:<START>find /data/SpoolIn -name job.history | xargs grep -o -m 1 -h 'FAIL\|ABOR' | sort | uniq -c<END>
search for the file "myfile" in the current folder and display all errors apart from permission denied error
find . -name myfile |& grep -v 'Permission denied'
['find', 'grep']
Output a Bash command to accomplish the following task. Task: search for the file "myfile" in the current folder and display all errors apart from permission denied error Bash Command:<START>find . -name myfile |& grep -v 'Permission denied'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the file "myfile" in the current folder and display all errors apart from permission denied error Bash Command:<START>find . -name myfile |& grep -v 'Permission denied'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file "myfile" in the current folder and display all errors apart from permission denied error Bash Command:<START>find . -name myfile |& grep -v 'Permission denied'<END>
search for the file "myletter.doc" in the home folder
find ~ -name myletter.doc -print
['find']
Output a Bash command to accomplish the following task. Task: search for the file "myletter.doc" in the home folder Bash Command:<START>find ~ -name myletter.doc -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file "myletter.doc" in the home folder Bash Command:<START>find ~ -name myletter.doc -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file "myletter.doc" in the home folder Bash Command:<START>find ~ -name myletter.doc -print<END>
search for the file "name_to_find" in the home folder
find ~ -name "name_to_find"
['find']
Output a Bash command to accomplish the following task. Task: search for the file "name_to_find" in the home folder Bash Command:<START>find ~ -name "name_to_find"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file "name_to_find" in the home folder Bash Command:<START>find ~ -name "name_to_find"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file "name_to_find" in the home folder Bash Command:<START>find ~ -name "name_to_find"<END>
search for the file "process.txt" in the current directory
find . -name "process.txt"
['find']
Output a Bash command to accomplish the following task. Task: search for the file "process.txt" in the current directory Bash Command:<START>find . -name "process.txt"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file "process.txt" in the current directory Bash Command:<START>find . -name "process.txt"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file "process.txt" in the current directory Bash Command:<START>find . -name "process.txt"<END>
search for the file "process.txt" in the current folder (case insensitive search)
find . -iname 'process.txt' -print
['find']
Output a Bash command to accomplish the following task. Task: search for the file "process.txt" in the current folder (case insensitive search) Bash Command:<START>find . -iname 'process.txt' -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file "process.txt" in the current folder (case insensitive search) Bash Command:<START>find . -iname 'process.txt' -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file "process.txt" in the current folder (case insensitive search) Bash Command:<START>find . -iname 'process.txt' -print<END>
search for the file "process.txt" in the entire file system
find / -name "process.txt"
['find']
Output a Bash command to accomplish the following task. Task: search for the file "process.txt" in the entire file system Bash Command:<START>find / -name "process.txt"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file "process.txt" in the entire file system Bash Command:<START>find / -name "process.txt"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file "process.txt" in the entire file system Bash Command:<START>find / -name "process.txt"<END>
search for the file "process.txt" in the entire file system (case insensitive search)
find / -iname 'process.txt' -print
['find']
Output a Bash command to accomplish the following task. Task: search for the file "process.txt" in the entire file system (case insensitive search) Bash Command:<START>find / -iname 'process.txt' -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file "process.txt" in the entire file system (case insensitive search) Bash Command:<START>find / -iname 'process.txt' -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file "process.txt" in the entire file system (case insensitive search) Bash Command:<START>find / -iname 'process.txt' -print<END>
search for the file centos in /usr folder ( case insenstive search )
find /usr -iname centos
['find']
Output a Bash command to accomplish the following task. Task: search for the file centos in /usr folder ( case insenstive search ) Bash Command:<START>find /usr -iname centos<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file centos in /usr folder ( case insenstive search ) Bash Command:<START>find /usr -iname centos<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file centos in /usr folder ( case insenstive search ) Bash Command:<START>find /usr -iname centos<END>
search for the file chapter1 in the folder /work
find /work -name chapter1
['find']
Output a Bash command to accomplish the following task. Task: search for the file chapter1 in the folder /work Bash Command:<START>find /work -name chapter1<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file chapter1 in the folder /work Bash Command:<START>find /work -name chapter1<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file chapter1 in the folder /work Bash Command:<START>find /work -name chapter1<END>
search for the file filename in the entire file system
find / -name filename
['find']
Output a Bash command to accomplish the following task. Task: search for the file filename in the entire file system Bash Command:<START>find / -name filename<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file filename in the entire file system Bash Command:<START>find / -name filename<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file filename in the entire file system Bash Command:<START>find / -name filename<END>
search for the file foo.txt in the current folder and open it in vi editor
find -name foo.txt -execdir vim '{}' ';'
['find']
Output a Bash command to accomplish the following task. Task: search for the file foo.txt in the current folder and open it in vi editor Bash Command:<START>find -name foo.txt -execdir vim '{}' ';'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file foo.txt in the current folder and open it in vi editor Bash Command:<START>find -name foo.txt -execdir vim '{}' ';'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file foo.txt in the current folder and open it in vi editor Bash Command:<START>find -name foo.txt -execdir vim '{}' ';'<END>
search for the file foo.txt in the entire file system
find / -name foo.txt
['find']
Output a Bash command to accomplish the following task. Task: search for the file foo.txt in the entire file system Bash Command:<START>find / -name foo.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file foo.txt in the entire file system Bash Command:<START>find / -name foo.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file foo.txt in the entire file system Bash Command:<START>find / -name foo.txt<END>
search for the file in the entire file system which has the words "filename" in its name
find / -name ”*filename*”
['find']
Output a Bash command to accomplish the following task. Task: search for the file in the entire file system which has the words "filename" in its name Bash Command:<START>find / -name ”*filename*”<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file in the entire file system which has the words "filename" in its name Bash Command:<START>find / -name ”*filename*”<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file in the entire file system which has the words "filename" in its name Bash Command:<START>find / -name ”*filename*”<END>
search for the file job.hostory in the folder "/data/Spoolln"
find /data/SpoolIn -name job.history
['find']
Output a Bash command to accomplish the following task. Task: search for the file job.hostory in the folder "/data/Spoolln" Bash Command:<START>find /data/SpoolIn -name job.history<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file job.hostory in the folder "/data/Spoolln" Bash Command:<START>find /data/SpoolIn -name job.history<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file job.hostory in the folder "/data/Spoolln" Bash Command:<START>find /data/SpoolIn -name job.history<END>
search for the file picasso in the folder /home/calvin/ (case insensitive search)
find /home/calvin/ -iname “picasso”
['find']
Output a Bash command to accomplish the following task. Task: search for the file picasso in the folder /home/calvin/ (case insensitive search) Bash Command:<START>find /home/calvin/ -iname “picasso”<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file picasso in the folder /home/calvin/ (case insensitive search) Bash Command:<START>find /home/calvin/ -iname “picasso”<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file picasso in the folder /home/calvin/ (case insensitive search) Bash Command:<START>find /home/calvin/ -iname “picasso”<END>
search for the file test in the current folder
find . -name test
['find', 'test']
Output a Bash command to accomplish the following task. Task: search for the file test in the current folder Bash Command:<START>find . -name test<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # test\n\n> Check file types and compare values.\n> Returns 0 if the condition evaluates to true, 1 if it evaluates to false.\n> More information: <https://www.gnu.org/software/coreutils/test>.\n\n- Test if a given variable is equal to a given string:\n\n`test "{{$MY_VAR}}" = "{{/bin/zsh}}"`\n\n- Test if a given variable is empty:\n\n`test -z "{{$GIT_BRANCH}}"`\n\n- Test if a file exists:\n\n`test -f "{{path/to/file_or_directory}}"`\n\n- Test if a directory does not exist:\n\n`test ! -d "{{path/to/directory}}"`\n\n- If A is true, then do B, or C in the case of an error (notice that C may run even if A fails):\n\n`test {{condition}} && {{echo "true"}} || {{echo "false"}}`\n Task: search for the file test in the current folder Bash Command:<START>find . -name test<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. test(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training test(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TEST(1) User Commands TEST(1) NAME top test - check file types and compare values SYNOPSIS top test EXPRESSION test [ EXPRESSION ] [ ] [ OPTION DESCRIPTION top Exit with the status determined by EXPRESSION. --help display this help and exit --version output version information and exit An omitted EXPRESSION defaults to false. Otherwise, EXPRESSION is true or false and sets exit status. It is one of: ( EXPRESSION ) EXPRESSION is true ! EXPRESSION EXPRESSION is false EXPRESSION1 -a EXPRESSION2 both EXPRESSION1 and EXPRESSION2 are true EXPRESSION1 -o EXPRESSION2 either EXPRESSION1 or EXPRESSION2 is true -n STRING the length of STRING is nonzero STRING equivalent to -n STRING -z STRING the length of STRING is zero STRING1 = STRING2 the strings are equal STRING1 != STRING2 the strings are not equal INTEGER1 -eq INTEGER2 INTEGER1 is equal to INTEGER2 INTEGER1 -ge INTEGER2 INTEGER1 is greater than or equal to INTEGER2 INTEGER1 -gt INTEGER2 INTEGER1 is greater than INTEGER2 INTEGER1 -le INTEGER2 INTEGER1 is less than or equal to INTEGER2 INTEGER1 -lt INTEGER2 INTEGER1 is less than INTEGER2 INTEGER1 -ne INTEGER2 INTEGER1 is not equal to INTEGER2 FILE1 -ef FILE2 FILE1 and FILE2 have the same device and inode numbers FILE1 -nt FILE2 FILE1 is newer (modification date) than FILE2 FILE1 -ot FILE2 FILE1 is older than FILE2 -b FILE FILE exists and is block special -c FILE FILE exists and is character special -d FILE FILE exists and is a directory -e FILE FILE exists -f FILE FILE exists and is a regular file -g FILE FILE exists and is set-group-ID -G FILE FILE exists and is owned by the effective group ID -h FILE FILE exists and is a symbolic link (same as -L) -k FILE FILE exists and has its sticky bit set -L FILE FILE exists and is a symbolic link (same as -h) -N FILE FILE exists and has been modified since it was last read -O FILE FILE exists and is owned by the effective user ID -p FILE FILE exists and is a named pipe -r FILE FILE exists and the user has read access -s FILE FILE exists and has a size greater than zero -S FILE FILE exists and is a socket -t FD file descriptor FD is opened on a terminal -u FILE FILE exists and its set-user-ID bit is set -w FILE FILE exists and the user has write access -x FILE FILE exists and the user has execute (or search) access Except for -h and -L, all FILE-related tests dereference symbolic links. Beware that parentheses need to be escaped (e.g., by backslashes) for shells. INTEGER may also be -l STRING, which evaluates to the length of STRING. NOTE: Binary -a and -o are inherently ambiguous. Use 'test EXPR1 && test EXPR2' or 'test EXPR1 || test EXPR2' instead. NOTE: [ honors the --help and --version options, but test does not. test treats each of those as it treats any other nonempty STRING. NOTE: your shell may have its own version of test and/or [, which usually supersedes the version described here. Please refer to your shell's documentation for details about the options it supports. AUTHOR top Written by Kevin Braunsdorf and Matthew Bradburn. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top access(2) Full documentation <https://www.gnu.org/software/coreutils/test> or available locally via: info '(coreutils) test invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 TEST(1) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file test in the current folder Bash Command:<START>find . -name test<END>
search for the file test.txt in the folders /home and /opt
find /home /opt -name test.txt
['find']
Output a Bash command to accomplish the following task. Task: search for the file test.txt in the folders /home and /opt Bash Command:<START>find /home /opt -name test.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file test.txt in the folders /home and /opt Bash Command:<START>find /home /opt -name test.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file test.txt in the folders /home and /opt Bash Command:<START>find /home /opt -name test.txt<END>
search for the file test2 in the current folder
find -name test2
['find']
Output a Bash command to accomplish the following task. Task: search for the file test2 in the current folder Bash Command:<START>find -name test2<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file test2 in the current folder Bash Command:<START>find -name test2<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file test2 in the current folder Bash Command:<START>find -name test2<END>
search for the file, filename.txt in the current folder
find . -name filename.txt
['find']
Output a Bash command to accomplish the following task. Task: search for the file, filename.txt in the current folder Bash Command:<START>find . -name filename.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file, filename.txt in the current folder Bash Command:<START>find . -name filename.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file, filename.txt in the current folder Bash Command:<START>find . -name filename.txt<END>
search for the file, filename.txt in the current folder ( case insensitive search )
find . -iname filename.txt
['find']
Output a Bash command to accomplish the following task. Task: search for the file, filename.txt in the current folder ( case insensitive search ) Bash Command:<START>find . -iname filename.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file, filename.txt in the current folder ( case insensitive search ) Bash Command:<START>find . -iname filename.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file, filename.txt in the current folder ( case insensitive search ) Bash Command:<START>find . -iname filename.txt<END>
search for the file, filename.txt in the folder /home
find /home -name filename.txt
['find']
Output a Bash command to accomplish the following task. Task: search for the file, filename.txt in the folder /home Bash Command:<START>find /home -name filename.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the file, filename.txt in the folder /home Bash Command:<START>find /home -name filename.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the file, filename.txt in the folder /home Bash Command:<START>find /home -name filename.txt<END>
search for the files "foo.txt" in the current folder
find . -name foo.txt
['find']
Output a Bash command to accomplish the following task. Task: search for the files "foo.txt" in the current folder Bash Command:<START>find . -name foo.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the files "foo.txt" in the current folder Bash Command:<START>find . -name foo.txt<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the files "foo.txt" in the current folder Bash Command:<START>find . -name foo.txt<END>
search for the files "foo.txt" in the current folder and rename it to foo.xml
find -name foo.txt -execdir rename 's/\.txt$/.xml/' '{}' ';'
['find', 'rename']
Output a Bash command to accomplish the following task. Task: search for the files "foo.txt" in the current folder and rename it to foo.xml Bash Command:<START>find -name foo.txt -execdir rename 's/\.txt$/.xml/' '{}' ';'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # rename\n\n> Rename multiple files.\n> Note: this page refers to the command from the `util-linux` package.\n> For the Perl version, see `file-rename` or `perl-rename`.\n> Warning: This command has no safeguards and will overwrite files without prompting.\n> More information: <https://manned.org/rename>.\n\n- Rename files using simple substitutions (substitute 'foo' with 'bar' wherever found):\n\n`rename {{foo}} {{bar}} {{*}}`\n\n- Dry-run - display which renames would occur without performing them:\n\n`rename -vn {{foo}} {{bar}} {{*}}`\n\n- Do not overwrite existing files:\n\n`rename -o {{foo}} {{bar}} {{*}}`\n\n- Change file extensions:\n\n`rename {{.ext}} {{.bak}} {{*.ext}}`\n\n- Prepend "foo" to all filenames in the current directory:\n\n`rename {{''}} {{'foo'}} {{*}}`\n\n- Rename a group of increasingly numbered files zero-padding the numbers up to 3 digits:\n\n`rename {{foo}} {{foo00}} {{foo?}} && rename {{foo}} {{foo0}} {{foo??}}`\n Task: search for the files "foo.txt" in the current folder and rename it to foo.xml Bash Command:<START>find -name foo.txt -execdir rename 's/\.txt$/.xml/' '{}' ';'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. rename(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training rename(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | WARNING | EDGE CASES | INTERACTIVE MODE | EXIT STATUS | EXAMPLES | SEE ALSO | REPORTING BUGS | AVAILABILITY RENAME(1) User Commands RENAME(1) NAME top rename - rename files SYNOPSIS top rename [options] expression replacement file... DESCRIPTION top rename will rename the specified files by replacing the first occurrence of expression in their name by replacement. OPTIONS top -s, --symlink Do not rename a symlink but change where it points. -v, --verbose Show which files were renamed, if any. -n, --no-act Do not make any changes; add --verbose to see what would be made. -a, --all Replace all occurrences of expression rather than only the first one. -l, --last Replace the last occurrence of expression rather than the first one. -o, --no-overwrite Do not overwrite existing files. When --symlink is active, do not overwrite symlinks pointing to existing targets. -i, --interactive Ask before overwriting existing files. -h, --help Display help text and exit. -V, --version Print version and exit. WARNING top The renaming has no safeguards by default or without any one of the options --no-overwrite, --interactive or --no-act. If the user has permission to rewrite file names, the command will perform the action without any questions. For example, the result can be quite drastic when the command is run as root in the /lib directory. Always make a backup before running the command, unless you truly know what you are doing. EDGE CASES top If the expression is empty, then by default replacement will be added to the start of the filename. With --all, replacement will be inserted in between every two characters of the filename, as well as at the start and end. Normally, only the final path component of a filename is updated. (Or with --symlink, only the final path component of the link.) But if either expression or replacement contains a /, the full path is updated. This can cause a file to be moved between folders. Creating folders, and moving files between filesystems, is not supported. INTERACTIVE MODE top As most standard utilities rename can be used with a terminal device (tty in short) in canonical mode, where the line is buffered by the tty and you press ENTER to validate the user input. If you put your tty in cbreak mode however, rename requires only a single key press to answer the prompt. To set cbreak mode, run for example: sh -c 'stty -icanon min 1; "$0" "$@"; stty icanon' rename -i from to files EXIT STATUS top 0 all requested rename operations were successful 1 all rename operations failed 2 some rename operations failed 4 nothing was renamed 64 unanticipated error occurred EXAMPLES top Given the files foo1, ..., foo9, foo10, ..., foo278, the commands rename foo foo00 foo? rename foo foo0 foo?? will turn them into foo001, ..., foo009, foo010, ..., foo278. And rename .htm .html *.htm will fix the extension of your html files. Provide an empty string for shortening: rename '_with_long_name' '' file_with_long_name.* will remove the substring in the filenames. SEE ALSO top mv(1) REPORTING BUGS top For bug reports, use the issue tracker at https://github.com/util-linux/util-linux/issues. AVAILABILITY top The rename command is part of the util-linux package which can be downloaded from Linux Kernel Archive <https://www.kernel.org/pub/linux/utils/util-linux/>. This page is part of the util-linux (a random collection of Linux utilities) project. Information about the project can be found at https://www.kernel.org/pub/linux/utils/util-linux/. If you have a bug report for this manual page, send it to util-linux@vger.kernel.org. This page was obtained from the project's upstream Git repository git://git.kernel.org/pub/scm/utils/util-linux/util-linux.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-12-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org util-linux 2.39.594-1e0ad 2023-07-19 RENAME(1) Pages that refer to this page: rename(2), strverscmp(3) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the files "foo.txt" in the current folder and rename it to foo.xml Bash Command:<START>find -name foo.txt -execdir rename 's/\.txt$/.xml/' '{}' ';'<END>
search for the files in the current folder which begin with the word "kt" followed by a digit
find . -name 'kt[0-9] '
['find']
Output a Bash command to accomplish the following task. Task: search for the files in the current folder which begin with the word "kt" followed by a digit Bash Command:<START>find . -name 'kt[0-9] '<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the files in the current folder which begin with the word "kt" followed by a digit Bash Command:<START>find . -name 'kt[0-9] '<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the files in the current folder which begin with the word "kt" followed by a digit Bash Command:<START>find . -name 'kt[0-9] '<END>
search for the files which contain the word start in their name excluding search in ./proc, ./sys, ./run folders
find . -path ./proc -prune -or -path ./sys -prune -or -path ./run -prune -or -iname '*start*' -print
['find']
Output a Bash command to accomplish the following task. Task: search for the files which contain the word start in their name excluding search in ./proc, ./sys, ./run folders Bash Command:<START>find . -path ./proc -prune -or -path ./sys -prune -or -path ./run -prune -or -iname '*start*' -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the files which contain the word start in their name excluding search in ./proc, ./sys, ./run folders Bash Command:<START>find . -path ./proc -prune -or -path ./sys -prune -or -path ./run -prune -or -iname '*start*' -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the files which contain the word start in their name excluding search in ./proc, ./sys, ./run folders Bash Command:<START>find . -path ./proc -prune -or -path ./sys -prune -or -path ./run -prune -or -iname '*start*' -print<END>
search for the files with the name "temp" and which have not been accessed in the last 7*24 hours in the /usr folder
find /usr -name temp -atime +7 -print
['find']
Output a Bash command to accomplish the following task. Task: search for the files with the name "temp" and which have not been accessed in the last 7*24 hours in the /usr folder Bash Command:<START>find /usr -name temp -atime +7 -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the files with the name "temp" and which have not been accessed in the last 7*24 hours in the /usr folder Bash Command:<START>find /usr -name temp -atime +7 -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the files with the name "temp" and which have not been accessed in the last 7*24 hours in the /usr folder Bash Command:<START>find /usr -name temp -atime +7 -print<END>
search for the folder .dummy and remove it from the folder "Test folder"
find "Test Folder" -type d -name '.dummy' -delete
['find']
Output a Bash command to accomplish the following task. Task: search for the folder .dummy and remove it from the folder "Test folder" Bash Command:<START>find "Test Folder" -type d -name '.dummy' -delete<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the folder .dummy and remove it from the folder "Test folder" Bash Command:<START>find "Test Folder" -type d -name '.dummy' -delete<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the folder .dummy and remove it from the folder "Test folder" Bash Command:<START>find "Test Folder" -type d -name '.dummy' -delete<END>
search for the folder .dummy and remove it from the folder "Test folder"
find "Test Folder" -type d -name .dummy -exec rm -rf \"{}\" \;
['find', 'rm']
Output a Bash command to accomplish the following task. Task: search for the folder .dummy and remove it from the folder "Test folder" Bash Command:<START>find "Test Folder" -type d -name .dummy -exec rm -rf \"{}\" \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # rm\n\n> Remove files or directories.\n> See also: `rmdir`.\n> More information: <https://www.gnu.org/software/coreutils/rm>.\n\n- Remove specific files:\n\n`rm {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files ignoring nonexistent ones:\n\n`rm --force {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files interactively prompting before each removal:\n\n`rm --interactive {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files printing info about each removal:\n\n`rm --verbose {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files and directories recursively:\n\n`rm --recursive {{path/to/file_or_directory1 path/to/file_or_directory2 ...}}`\n Task: search for the folder .dummy and remove it from the folder "Test folder" Bash Command:<START>find "Test Folder" -type d -name .dummy -exec rm -rf \"{}\" \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. rm(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training rm(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON RM(1) User Commands RM(1) NAME top rm - remove files or directories SYNOPSIS top rm [OPTION]... [FILE]... DESCRIPTION top This manual page documents the GNU version of rm. rm removes each specified file. By default, it does not remove directories. If the -I or --interactive=once option is given, and there are more than three files or the -r, -R, or --recursive are given, then rm prompts the user for whether to proceed with the entire operation. If the response is not affirmative, the entire command is aborted. Otherwise, if a file is unwritable, standard input is a terminal, and the -f or --force option is not given, or the -i or --interactive=always option is given, rm prompts the user for whether to remove the file. If the response is not affirmative, the file is skipped. OPTIONS top Remove (unlink) the FILE(s). -f, --force ignore nonexistent files and arguments, never prompt -i prompt before every removal -I prompt once before removing more than three files, or when removing recursively; less intrusive than -i, while still giving protection against most mistakes --interactive[=WHEN] prompt according to WHEN: never, once (-I), or always (-i); without WHEN, prompt always --one-file-system when removing a hierarchy recursively, skip any directory that is on a file system different from that of the corresponding command line argument --no-preserve-root do not treat '/' specially --preserve-root[=all] do not remove '/' (default); with 'all', reject any command line argument on a separate device from its parent -r, -R, --recursive remove directories and their contents recursively -d, --dir remove empty directories -v, --verbose explain what is being done --help display this help and exit --version output version information and exit By default, rm does not remove directories. Use the --recursive (-r or -R) option to remove each listed directory, too, along with all of its contents. To remove a file whose name starts with a '-', for example '-foo', use one of these commands: rm -- -foo rm ./-foo Note that if you use rm to remove a file, it might be possible to recover some of its contents, given sufficient expertise and/or time. For greater assurance that the contents are truly unrecoverable, consider using shred(1). AUTHOR top Written by Paul Rubin, David MacKenzie, Richard M. Stallman, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top unlink(1), unlink(2), chattr(1), shred(1) Full documentation <https://www.gnu.org/software/coreutils/rm> or available locally via: info '(coreutils) rm invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 RM(1) Pages that refer to this page: rmdir(2), unlink(2), remove(3), mq_overview(7), symlink(7), debugfs(8), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the folder .dummy and remove it from the folder "Test folder" Bash Command:<START>find "Test Folder" -type d -name .dummy -exec rm -rf \"{}\" \;<END>
search for the folder .dummy in the entire directory structure of "test folder" and remove it.
find -depth "Test Folder" -type d -name .dummy -exec rm -rf \{\} \;
['find', 'rm']
Output a Bash command to accomplish the following task. Task: search for the folder .dummy in the entire directory structure of "test folder" and remove it. Bash Command:<START>find -depth "Test Folder" -type d -name .dummy -exec rm -rf \{\} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # rm\n\n> Remove files or directories.\n> See also: `rmdir`.\n> More information: <https://www.gnu.org/software/coreutils/rm>.\n\n- Remove specific files:\n\n`rm {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files ignoring nonexistent ones:\n\n`rm --force {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files interactively prompting before each removal:\n\n`rm --interactive {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files printing info about each removal:\n\n`rm --verbose {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files and directories recursively:\n\n`rm --recursive {{path/to/file_or_directory1 path/to/file_or_directory2 ...}}`\n Task: search for the folder .dummy in the entire directory structure of "test folder" and remove it. Bash Command:<START>find -depth "Test Folder" -type d -name .dummy -exec rm -rf \{\} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. rm(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training rm(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON RM(1) User Commands RM(1) NAME top rm - remove files or directories SYNOPSIS top rm [OPTION]... [FILE]... DESCRIPTION top This manual page documents the GNU version of rm. rm removes each specified file. By default, it does not remove directories. If the -I or --interactive=once option is given, and there are more than three files or the -r, -R, or --recursive are given, then rm prompts the user for whether to proceed with the entire operation. If the response is not affirmative, the entire command is aborted. Otherwise, if a file is unwritable, standard input is a terminal, and the -f or --force option is not given, or the -i or --interactive=always option is given, rm prompts the user for whether to remove the file. If the response is not affirmative, the file is skipped. OPTIONS top Remove (unlink) the FILE(s). -f, --force ignore nonexistent files and arguments, never prompt -i prompt before every removal -I prompt once before removing more than three files, or when removing recursively; less intrusive than -i, while still giving protection against most mistakes --interactive[=WHEN] prompt according to WHEN: never, once (-I), or always (-i); without WHEN, prompt always --one-file-system when removing a hierarchy recursively, skip any directory that is on a file system different from that of the corresponding command line argument --no-preserve-root do not treat '/' specially --preserve-root[=all] do not remove '/' (default); with 'all', reject any command line argument on a separate device from its parent -r, -R, --recursive remove directories and their contents recursively -d, --dir remove empty directories -v, --verbose explain what is being done --help display this help and exit --version output version information and exit By default, rm does not remove directories. Use the --recursive (-r or -R) option to remove each listed directory, too, along with all of its contents. To remove a file whose name starts with a '-', for example '-foo', use one of these commands: rm -- -foo rm ./-foo Note that if you use rm to remove a file, it might be possible to recover some of its contents, given sufficient expertise and/or time. For greater assurance that the contents are truly unrecoverable, consider using shred(1). AUTHOR top Written by Paul Rubin, David MacKenzie, Richard M. Stallman, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top unlink(1), unlink(2), chattr(1), shred(1) Full documentation <https://www.gnu.org/software/coreutils/rm> or available locally via: info '(coreutils) rm invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 RM(1) Pages that refer to this page: rmdir(2), unlink(2), remove(3), mq_overview(7), symlink(7), debugfs(8), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the folder .dummy in the entire directory structure of "test folder" and remove it. Bash Command:<START>find -depth "Test Folder" -type d -name .dummy -exec rm -rf \{\} \;<END>
search for the host "slc02oxm.us.oracle.com" in all the xml files in the current folder and display the files which has the matched content
find -name “*.xml” -exec grep -l “slc02oxm.us.oracle.com” {} \;
['find', 'grep']
Output a Bash command to accomplish the following task. Task: search for the host "slc02oxm.us.oracle.com" in all the xml files in the current folder and display the files which has the matched content Bash Command:<START>find -name “*.xml” -exec grep -l “slc02oxm.us.oracle.com” {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the host "slc02oxm.us.oracle.com" in all the xml files in the current folder and display the files which has the matched content Bash Command:<START>find -name “*.xml” -exec grep -l “slc02oxm.us.oracle.com” {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the host "slc02oxm.us.oracle.com" in all the xml files in the current folder and display the files which has the matched content Bash Command:<START>find -name “*.xml” -exec grep -l “slc02oxm.us.oracle.com” {} \;<END>
search for the ip "192.168.1.5" in all the files in /etc folder
find /etc/ -iname "*" | xargs grep '192.168.1.5'
['find', 'xargs', 'grep']
Output a Bash command to accomplish the following task. Task: search for the ip "192.168.1.5" in all the files in /etc folder Bash Command:<START>find /etc/ -iname "*" | xargs grep '192.168.1.5'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the ip "192.168.1.5" in all the files in /etc folder Bash Command:<START>find /etc/ -iname "*" | xargs grep '192.168.1.5'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the ip "192.168.1.5" in all the files in /etc folder Bash Command:<START>find /etc/ -iname "*" | xargs grep '192.168.1.5'<END>
search for the pattern "tgt/etc/file1" in the files tgt/etc/file2, tgt/etc/file3
find . -type f -name \* | grep tgt/etc/file1 tgt/etc/file2 tgt/etc/file3
['find', 'grep']
Output a Bash command to accomplish the following task. Task: search for the pattern "tgt/etc/file1" in the files tgt/etc/file2, tgt/etc/file3 Bash Command:<START>find . -type f -name \* | grep tgt/etc/file1 tgt/etc/file2 tgt/etc/file3<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the pattern "tgt/etc/file1" in the files tgt/etc/file2, tgt/etc/file3 Bash Command:<START>find . -type f -name \* | grep tgt/etc/file1 tgt/etc/file2 tgt/etc/file3<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the pattern "tgt/etc/file1" in the files tgt/etc/file2, tgt/etc/file3 Bash Command:<START>find . -type f -name \* | grep tgt/etc/file1 tgt/etc/file2 tgt/etc/file3<END>
search for the pattern in all the regular/normal files in the entire file system
find / -type f -print0 | xargs -0 grep -i pattern
['find', 'xargs', 'grep']
Output a Bash command to accomplish the following task. Task: search for the pattern in all the regular/normal files in the entire file system Bash Command:<START>find / -type f -print0 | xargs -0 grep -i pattern<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the pattern in all the regular/normal files in the entire file system Bash Command:<START>find / -type f -print0 | xargs -0 grep -i pattern<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the pattern in all the regular/normal files in the entire file system Bash Command:<START>find / -type f -print0 | xargs -0 grep -i pattern<END>
search for the regular/normal file "Dateiname" in the entire file system
find / -type f -iname "Dateiname"
['find']
Output a Bash command to accomplish the following task. Task: search for the regular/normal file "Dateiname" in the entire file system Bash Command:<START>find / -type f -iname "Dateiname"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the regular/normal file "Dateiname" in the entire file system Bash Command:<START>find / -type f -iname "Dateiname"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the regular/normal file "Dateiname" in the entire file system Bash Command:<START>find / -type f -iname "Dateiname"<END>
search for the regular/normal file "foo.bar" and force delete it
find /home -name foo.bar -type f -exec rm -f "{}" ';'
['find', 'rm']
Output a Bash command to accomplish the following task. Task: search for the regular/normal file "foo.bar" and force delete it Bash Command:<START>find /home -name foo.bar -type f -exec rm -f "{}" ';'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # rm\n\n> Remove files or directories.\n> See also: `rmdir`.\n> More information: <https://www.gnu.org/software/coreutils/rm>.\n\n- Remove specific files:\n\n`rm {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files ignoring nonexistent ones:\n\n`rm --force {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files interactively prompting before each removal:\n\n`rm --interactive {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files printing info about each removal:\n\n`rm --verbose {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files and directories recursively:\n\n`rm --recursive {{path/to/file_or_directory1 path/to/file_or_directory2 ...}}`\n Task: search for the regular/normal file "foo.bar" and force delete it Bash Command:<START>find /home -name foo.bar -type f -exec rm -f "{}" ';'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. rm(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training rm(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON RM(1) User Commands RM(1) NAME top rm - remove files or directories SYNOPSIS top rm [OPTION]... [FILE]... DESCRIPTION top This manual page documents the GNU version of rm. rm removes each specified file. By default, it does not remove directories. If the -I or --interactive=once option is given, and there are more than three files or the -r, -R, or --recursive are given, then rm prompts the user for whether to proceed with the entire operation. If the response is not affirmative, the entire command is aborted. Otherwise, if a file is unwritable, standard input is a terminal, and the -f or --force option is not given, or the -i or --interactive=always option is given, rm prompts the user for whether to remove the file. If the response is not affirmative, the file is skipped. OPTIONS top Remove (unlink) the FILE(s). -f, --force ignore nonexistent files and arguments, never prompt -i prompt before every removal -I prompt once before removing more than three files, or when removing recursively; less intrusive than -i, while still giving protection against most mistakes --interactive[=WHEN] prompt according to WHEN: never, once (-I), or always (-i); without WHEN, prompt always --one-file-system when removing a hierarchy recursively, skip any directory that is on a file system different from that of the corresponding command line argument --no-preserve-root do not treat '/' specially --preserve-root[=all] do not remove '/' (default); with 'all', reject any command line argument on a separate device from its parent -r, -R, --recursive remove directories and their contents recursively -d, --dir remove empty directories -v, --verbose explain what is being done --help display this help and exit --version output version information and exit By default, rm does not remove directories. Use the --recursive (-r or -R) option to remove each listed directory, too, along with all of its contents. To remove a file whose name starts with a '-', for example '-foo', use one of these commands: rm -- -foo rm ./-foo Note that if you use rm to remove a file, it might be possible to recover some of its contents, given sufficient expertise and/or time. For greater assurance that the contents are truly unrecoverable, consider using shred(1). AUTHOR top Written by Paul Rubin, David MacKenzie, Richard M. Stallman, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top unlink(1), unlink(2), chattr(1), shred(1) Full documentation <https://www.gnu.org/software/coreutils/rm> or available locally via: info '(coreutils) rm invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 RM(1) Pages that refer to this page: rmdir(2), unlink(2), remove(3), mq_overview(7), symlink(7), debugfs(8), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the regular/normal file "foo.bar" and force delete it Bash Command:<START>find /home -name foo.bar -type f -exec rm -f "{}" ';'<END>
search for the regular/normal file "myfile" in the current folder excluding search in the paths of "work" and "home" sub directories
find . \( -name work -o -name home \) -prune -o -name myfile -type f -print
['find']
Output a Bash command to accomplish the following task. Task: search for the regular/normal file "myfile" in the current folder excluding search in the paths of "work" and "home" sub directories Bash Command:<START>find . \( -name work -o -name home \) -prune -o -name myfile -type f -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the regular/normal file "myfile" in the current folder excluding search in the paths of "work" and "home" sub directories Bash Command:<START>find . \( -name work -o -name home \) -prune -o -name myfile -type f -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the regular/normal file "myfile" in the current folder excluding search in the paths of "work" and "home" sub directories Bash Command:<START>find . \( -name work -o -name home \) -prune -o -name myfile -type f -print<END>
search for the regular/normal file 'myfile' in the folder /root excluding those that are present in the "work" directory
find /root/ -name 'work' -prune -o -name myfile -type f -print
['find']
Output a Bash command to accomplish the following task. Task: search for the regular/normal file 'myfile' in the folder /root excluding those that are present in the "work" directory Bash Command:<START>find /root/ -name 'work' -prune -o -name myfile -type f -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the regular/normal file 'myfile' in the folder /root excluding those that are present in the "work" directory Bash Command:<START>find /root/ -name 'work' -prune -o -name myfile -type f -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the regular/normal file 'myfile' in the folder /root excluding those that are present in the "work" directory Bash Command:<START>find /root/ -name 'work' -prune -o -name myfile -type f -print<END>
search for the regular/normal file 'myfile' in the folder /root excluding those that are present in the /root/work directory
find /root/ -path '/root/work' -prune -o -name myfile -type f -print
['find']
Output a Bash command to accomplish the following task. Task: search for the regular/normal file 'myfile' in the folder /root excluding those that are present in the /root/work directory Bash Command:<START>find /root/ -path '/root/work' -prune -o -name myfile -type f -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search for the regular/normal file 'myfile' in the folder /root excluding those that are present in the /root/work directory Bash Command:<START>find /root/ -path '/root/work' -prune -o -name myfile -type f -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the regular/normal file 'myfile' in the folder /root excluding those that are present in the /root/work directory Bash Command:<START>find /root/ -path '/root/work' -prune -o -name myfile -type f -print<END>
search for the regulars file starting with HSTD which have been modified yesterday from day start and copy them to /path/tonew/dir
find . -type f -iname ‘HSTD*’ -daystart -mtime 1 -exec cp {} /path/to new/dir/ \;
['find', 'cp']
Output a Bash command to accomplish the following task. Task: search for the regulars file starting with HSTD which have been modified yesterday from day start and copy them to /path/tonew/dir Bash Command:<START>find . -type f -iname ‘HSTD*’ -daystart -mtime 1 -exec cp {} /path/to new/dir/ \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # cp\n\n> Copy files and directories.\n> More information: <https://www.gnu.org/software/coreutils/cp>.\n\n- Copy a file to another location:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_file.ext}}`\n\n- Copy a file into another directory, keeping the filename:\n\n`cp {{path/to/source_file.ext}} {{path/to/target_parent_directory}}`\n\n- Recursively copy a directory's contents to another location (if the destination exists, the directory is copied inside it):\n\n`cp -r {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy a directory recursively, in verbose mode (shows files as they are copied):\n\n`cp -vr {{path/to/source_directory}} {{path/to/target_directory}}`\n\n- Copy multiple files at once to a directory:\n\n`cp -t {{path/to/destination_directory}} {{path/to/file1 path/to/file2 ...}}`\n\n- Copy all files with a specific extension to another location, in interactive mode (prompts user before overwriting):\n\n`cp -i {{*.ext}} {{path/to/target_directory}}`\n\n- Follow symbolic links before copying:\n\n`cp -L {{link}} {{path/to/target_directory}}`\n\n- Use the full path of source files, creating any missing intermediate directories when copying:\n\n`cp --parents {{source/path/to/file}} {{path/to/target_file}}`\n Task: search for the regulars file starting with HSTD which have been modified yesterday from day start and copy them to /path/tonew/dir Bash Command:<START>find . -type f -iname ‘HSTD*’ -daystart -mtime 1 -exec cp {} /path/to new/dir/ \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. cp(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training cp(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON CP(1) User Commands CP(1) NAME top cp - copy files and directories SYNOPSIS top cp [OPTION]... [-T] SOURCE DEST cp [OPTION]... SOURCE... DIRECTORY cp [OPTION]... -t DIRECTORY SOURCE... DESCRIPTION top Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY. Mandatory arguments to long options are mandatory for short options too. -a, --archive same as -dR --preserve=all --attributes-only don't copy the file data, just the attributes --backup[=CONTROL] make a backup of each existing destination file -b like --backup but does not accept an argument --copy-contents copy contents of special files when recursive -d same as --no-dereference --preserve=links --debug explain how a file is copied. Implies -v -f, --force if an existing destination file cannot be opened, remove it and try again (this option is ignored when the -n option is also used) -i, --interactive prompt before overwrite (overrides a previous -n option) -H follow command-line symbolic links in SOURCE -l, --link hard link files instead of copying -L, --dereference always follow symbolic links in SOURCE -n, --no-clobber do not overwrite an existing file (overrides a -u or previous -i option). See also --update -P, --no-dereference never follow symbolic links in SOURCE -p same as --preserve=mode,ownership,timestamps --preserve[=ATTR_LIST] preserve the specified attributes --no-preserve=ATTR_LIST don't preserve the specified attributes --parents use full source file name under DIRECTORY -R, -r, --recursive copy directories recursively --reflink[=WHEN] control clone/CoW copies. See below --remove-destination remove each existing destination file before attempting to open it (contrast with --force) --sparse=WHEN control creation of sparse files. See below --strip-trailing-slashes remove any trailing slashes from each SOURCE argument -s, --symbolic-link make symbolic links instead of copying -S, --suffix=SUFFIX override the usual backup suffix -t, --target-directory=DIRECTORY copy all SOURCE arguments into DIRECTORY -T, --no-target-directory treat DEST as a normal file --update[=UPDATE] control which existing files are updated; UPDATE={all,none,older(default)}. See below -u equivalent to --update[=older] -v, --verbose explain what is being done -x, --one-file-system stay on this file system -Z set SELinux security context of destination file to default type --context[=CTX] like -Z, or if CTX is specified then set the SELinux or SMACK security context to CTX --help display this help and exit --version output version information and exit ATTR_LIST is a comma-separated list of attributes. Attributes are 'mode' for permissions (including any ACL and xattr permissions), 'ownership' for user and group, 'timestamps' for file timestamps, 'links' for hard links, 'context' for security context, 'xattr' for extended attributes, and 'all' for all attributes. By default, sparse SOURCE files are detected by a crude heuristic and the corresponding DEST file is made sparse as well. That is the behavior selected by --sparse=auto. Specify --sparse=always to create a sparse DEST file whenever the SOURCE file contains a long enough sequence of zero bytes. Use --sparse=never to inhibit creation of sparse files. UPDATE controls which existing files in the destination are replaced. 'all' is the default operation when an --update option is not specified, and results in all existing files in the destination being replaced. 'none' is similar to the --no-clobber option, in that no files in the destination are replaced, but also skipped files do not induce a failure. 'older' is the default operation when --update is specified, and results in files being replaced if they're older than the corresponding source file. When --reflink[=always] is specified, perform a lightweight copy, where the data blocks are copied only when modified. If this is not possible the copy fails, or if --reflink=auto is specified, fall back to a standard copy. Use --reflink=never to ensure a standard copy is performed. The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable. Here are the values: none, off never make backups (even if --backup is given) numbered, t make numbered backups existing, nil numbered if numbered backups exist, simple otherwise simple, never always make simple backups As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file. AUTHOR top Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top install(1) Full documentation <https://www.gnu.org/software/coreutils/cp> or available locally via: info '(coreutils) cp invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 CP(1) Pages that refer to this page: install(1), pmlogmv(1), rsync(1), cpuset(7), symlink(7), e2image(8), readprofile(8), swapon(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the regulars file starting with HSTD which have been modified yesterday from day start and copy them to /path/tonew/dir Bash Command:<START>find . -type f -iname ‘HSTD*’ -daystart -mtime 1 -exec cp {} /path/to new/dir/ \;<END>
search for the word "damian" in all the regular/normal files in the /etc folder and display only the matched file name
find /etc -type f | xargs grep -l -i "damian"
['find', 'xargs', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word "damian" in all the regular/normal files in the /etc folder and display only the matched file name Bash Command:<START>find /etc -type f | xargs grep -l -i "damian"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word "damian" in all the regular/normal files in the /etc folder and display only the matched file name Bash Command:<START>find /etc -type f | xargs grep -l -i "damian"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word "damian" in all the regular/normal files in the /etc folder and display only the matched file name Bash Command:<START>find /etc -type f | xargs grep -l -i "damian"<END>
search for the word "foo" in all the regular/normal files in the directory "/path/to/dir"
find /path/to/dir -type f -print0 | xargs -0 grep -l "foo"
['find', 'xargs', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word "foo" in all the regular/normal files in the directory "/path/to/dir" Bash Command:<START>find /path/to/dir -type f -print0 | xargs -0 grep -l "foo"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word "foo" in all the regular/normal files in the directory "/path/to/dir" Bash Command:<START>find /path/to/dir -type f -print0 | xargs -0 grep -l "foo"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word "foo" in all the regular/normal files in the directory "/path/to/dir" Bash Command:<START>find /path/to/dir -type f -print0 | xargs -0 grep -l "foo"<END>
search for the word "foo" in all the regular/normal files with the name "file-pattern" in the directory "/path/to/dir"
find /path/to/dir/ -type f -name "file-pattern" -print0 | xargs -I {} -0 grep -l "foo" "{}"
['find', 'xargs', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word "foo" in all the regular/normal files with the name "file-pattern" in the directory "/path/to/dir" Bash Command:<START>find /path/to/dir/ -type f -name "file-pattern" -print0 | xargs -I {} -0 grep -l "foo" "{}"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word "foo" in all the regular/normal files with the name "file-pattern" in the directory "/path/to/dir" Bash Command:<START>find /path/to/dir/ -type f -name "file-pattern" -print0 | xargs -I {} -0 grep -l "foo" "{}"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word "foo" in all the regular/normal files with the name "file-pattern" in the directory "/path/to/dir" Bash Command:<START>find /path/to/dir/ -type f -name "file-pattern" -print0 | xargs -I {} -0 grep -l "foo" "{}"<END>
search for the word "methodNameHere" in all the python files in the folder "/mycool/project/" and display color on the matched lines in the output
find /mycool/project/ -type f -name "*.py" -print0 | xargs -I {} -0 grep -H --color "methodNameHere" "{}"
['find', 'xargs', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word "methodNameHere" in all the python files in the folder "/mycool/project/" and display color on the matched lines in the output Bash Command:<START>find /mycool/project/ -type f -name "*.py" -print0 | xargs -I {} -0 grep -H --color "methodNameHere" "{}"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word "methodNameHere" in all the python files in the folder "/mycool/project/" and display color on the matched lines in the output Bash Command:<START>find /mycool/project/ -type f -name "*.py" -print0 | xargs -I {} -0 grep -H --color "methodNameHere" "{}"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word "methodNameHere" in all the python files in the folder "/mycool/project/" and display color on the matched lines in the output Bash Command:<START>find /mycool/project/ -type f -name "*.py" -print0 | xargs -I {} -0 grep -H --color "methodNameHere" "{}"<END>
search for the word "mysql" in all the files in the current containing the word "notes" in their name
find . -iname "*notes*" | xargs grep -i mysql
['find', 'xargs', 'mysql', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word "mysql" in all the files in the current containing the word "notes" in their name Bash Command:<START>find . -iname "*notes*" | xargs grep -i mysql<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # mysql\n\n> The MySQL command-line tool.\n> More information: <https://www.mysql.com/>.\n\n- Connect to a database:\n\n`mysql {{database_name}}`\n\n- Connect to a database, user will be prompted for a password:\n\n`mysql -u {{user}} --password {{database_name}}`\n\n- Connect to a database on another host:\n\n`mysql -h {{database_host}} {{database_name}}`\n\n- Connect to a database through a Unix socket:\n\n`mysql --socket {{path/to/socket.sock}}`\n\n- Execute SQL statements in a script file (batch file):\n\n`mysql -e "source {{filename.sql}}" {{database_name}}`\n\n- Restore a database from a backup created with `mysqldump` (user will be prompted for a password):\n\n`mysql --user {{user}} --password {{database_name}} < {{path/to/backup.sql}}`\n\n- Restore all databases from a backup (user will be prompted for a password):\n\n`mysql --user {{user}} --password < {{path/to/backup.sql}}`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word "mysql" in all the files in the current containing the word "notes" in their name Bash Command:<START>find . -iname "*notes*" | xargs grep -i mysql<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. mysql(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training mysql(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | MYSQL OPTIONS | MYSQL COMMANDS | MYSQL SERVER-SIDE HELP | EXECUTING SQL STATEMENTS FROM A TEXT FILE | MYSQL TIPS | COPYRIGHT | NOTES | SEE ALSO | AUTHOR | COLOPHON MARIADB(1) MariaDB Database System MARIADB(1) NAME top mariadb - the MariaDB command-line tool (mysql is now a symlink to mariadb) SYNOPSIS top mysql [options] db_name DESCRIPTION top mysql is a simple SQL shell (with GNU readline capabilities). It supports interactive and non-interactive use. When used interactively, query results are presented in an ASCII-table format. When used non-interactively (for example, as a filter), the result is presented in tab-separated format. The output format can be changed using command options. If you have problems due to insufficient memory for large result sets, use the --quick option. This forces mysql to retrieve results from the server a row at a time rather than retrieving the entire result set and buffering it in memory before displaying it. This is done by returning the result set using the mysql_use_result() C API function in the client/server library rather than mysql_store_result(). Using mysql is very easy. Invoke it from the prompt of your command interpreter as follows: shell> mysql db_name Or: shell> mysql --user=user_name --password=your_password db_name Then type an SQL statement, end it with ;, \g, or \G and press Enter. Typing Control-C causes mysql to attempt to kill the current statement. If this cannot be done, or Control-C is typed again before the statement is killed, mysql exits. You can execute SQL statements in a script file (batch file) like this: shell> mysql db_name < script.sql > output.tab MYSQL OPTIONS top mysql supports the following options, which can be specified on the command line or in the [mysql], [client], [client-server] or [client-mariadb] option file groups. mysql also supports the options for processing option files. --help, -?, -I Display a help message and exit. --abort-source-on-error Abort 'source filename' operations in case of errors. --auto-rehash Enable automatic rehashing. This option is on by default, which enables database, table, and column name completion. Use --disable-auto-rehash, --no-auto-rehash, or --skip-auto-rehash to disable rehashing. That causes mysql to start faster, but you must issue the rehash command if you want to use name completion. To complete a name, enter the first part and press Tab. If the name is unambiguous, mysql completes it. Otherwise, you can press Tab again to see the possible names that begin with what you have typed so far. Completion does not occur if there is no default database. --auto-vertical-output Automatically switch to vertical output mode if the result is wider than the terminal width. --batch, -B Print results using tab as the column separator, with each row on a new line. With this option, mysql does not use the history file. Batch mode results in nontabular output format and escaping of special characters. Escaping may be disabled by using raw mode; see the description for the --raw option. --binary-mode Binary mode allows certain character sequences to be processed as data that would otherwise be treated with a special meaning by the parser. Specifically, this switch turns off parsing of all client commands except \C and DELIMITER in non-interactive mode (i.e., when binary mode is combined with either 1) piped input, 2) the --batch mysql option, or 3) the 'source' command). Also, in binary mode, occurrences of '\r\n' and ASCII '\0' are preserved within strings, whereas by default, '\r\n' is translated to '\n' and '\0' is disallowed in user input. --character-sets-dir=path The directory where character sets are installed. --column-names Write column names in results. --column-type-info, -m Display result set metadata. --comments, -c Whether to preserve comments in statements sent to the server. The default is --skip-comments (discard comments), enable with --comments (preserve comments). --compress, -C Compress all information sent between the client and the server if both support compression. --connect-timeout=seconds Set the number of seconds before connection timeout. (Default value is 0.) --database=db_name, -D db_name The database to use. --debug[=debug_options], -# [debug_options] Write a debugging log. A typical debug_options string is d:t:o,file_name. The default is d:t:o,/tmp/mysql.trace. --debug-check Print some debugging information when the program exits. --debug-info, -T Prints debugging information and memory and CPU usage statistics when the program exits. --default-auth=name Default authentication client-side plugin to use. --default-character-set=charset_name Use charset_name as the default character set for the client and connection. A common issue that can occur when the operating system uses utf8 or another multi-byte character set is that output from the mysql client is formatted incorrectly, due to the fact that the MariaDB client uses the latin1 character set by default. You can usually fix such issues by using this option to force the client to use the system character set instead. --defaults-extra-file=filename Set filename as the file to read default options from after the global defaults files has been read. Must be given as first option. --defaults-file=filename Set filename as the file to read default options from, override global defaults files. Must be given as first option. --defaults-group-suffix=suffix In addition to the groups named on the command line, read groups that have the given suffix. --delimiter=str Set the statement delimiter. The default is the semicolon character (;). --disable-named-commands Disable named commands. Use the \* form only, or use named commands only at the beginning of a line ending with a semicolon (;). mysql starts with this option enabled by default. However, even with this option, long-format commands still work from the first line. See the section called MYSQL COMMANDS. --enable-cleartext-plugin Obsolete option. Exists only for MySQL compatibility. --execute=statement, -e statement Execute the statement and quit. Disables --force and history file. The default output format is like that produced with --batch. --force, -f Continue even if an SQL error occurs. Sets --abort-source-on- error to 0. --host=host_name, -h host_name Connect to the MariaDB server on the given host. --html, -H Produce HTML output. --ignore-spaces, -i Ignore spaces after function names. Allows one to have spaces (including tab characters and new line characters) between function name and '('. The drawback is that this causes built in functions to become reserved words. --init-command=str SQL Command to execute when connecting to the MariaDB server. Will automatically be re-executed when reconnecting. --line-numbers Write line numbers for errors. Disable this with --skip-line-numbers. --local-infile[={0|1}] Enable or disable LOCAL capability for LOAD DATA INFILE. With no value, the option enables LOCAL. The option may be given as --local-infile=0 or --local-infile=1 to explicitly disable or enable LOCAL. Enabling LOCAL has no effect if the server does not also support it. --max-allowed-packet=num Set the maximum packet length to send to or receive from the server. (Default value is 16MB, largest 1GB.) --max-join-size=num Set the automatic limit for rows in a join when using --safe-updates. (Default value is 1,000,000.) --named-commands, -G Enable named mysql commands. Long-format commands are allowed, not just short-format commands. For example, quit and \q both are recognized. Use --skip-named-commands to disable named commands. See the section called MYSQL COMMANDS. Disabled by default.  --net-buffer-length=size Set the buffer size for TCP/IP and socket communication. (Default value is 16KB.) --no-auto-rehash, -A This has the same effect as --skip-auto-rehash. See the description for --auto-rehash. --no-beep, -b Do not beep when errors occur. --no-defaults Do not read default options from any option file. This must be given as the first argument. --one-database, -o Ignore statements except those those that occur while the default database is the one named on the command line. This filtering is limited, and based only on USE statements. This is useful for skipping updates to other databases in the binary log. --pager[=command] Use the given command for paging query output. If the command is omitted, the default pager is the value of your PAGER environment variable. Valid pagers are less, more, cat [> filename], and so forth. This option works only on Unix and only in interactive mode. To disable paging, use --skip-pager. the section called MYSQL COMMANDS, discusses output paging further. --password[=password], -p[password] The password to use when connecting to the server. If you use the short option form (-p), you cannot have a space between the option and the password. If you omit the password value following the --password or -p option on the command line, mysql prompts for one. Specifying a password on the command line should be considered insecure. You can use an option file to avoid giving the password on the command line. --pipe, -W On Windows, connect to the server via a named pipe. This option applies only if the server supports named-pipe connections. --plugin-dir=dir_name Directory for client-side plugins. --port=port_num, -P port_num The TCP/IP port number to use for the connection or 0 for default to, in order of preference, my.cnf, $MYSQL_TCP_PORT, /etc/services, built-in default (3306). Forces --protocol=tcp when specified on the command line without other connection properties. --print-defaults Print the program argument list and exit. This must be given as the first argument. --progress-reports Get progress reports for long running commands (such as ALTER TABLE). (Defaults to on; use --skip-progress-reports to disable.) --prompt=format_str Set the prompt to the specified format. The special sequences that the prompt can contain are described in the section called MYSQL COMMANDS. --protocol={TCP|SOCKET|PIPE|MEMORY} The connection protocol to use for connecting to the server. It is useful when the other connection parameters normally would cause a protocol to be used other than the one you want. --quick, -q Do not cache each query result, print each row as it is received. This may slow down the server if the output is suspended. With this option, mysql does not use the history file. --raw, -r For tabular output, the boxing around columns enables one column value to be distinguished from another. For nontabular output (such as is produced in batch mode or when the --batch or --silent option is given), special characters are escaped in the output so they can be identified easily. Newline, tab, NUL, and backslash are written as \n, \t, \0, and \\. The --raw option disables this character escaping. The following example demonstrates tabular versus nontabular output and the use of raw mode to disable escaping: % mysql mysql> SELECT CHAR(92); +----------+ | CHAR(92) | +----------+ | \ | +----------+ % mysql -s mysql> SELECT CHAR(92); CHAR(92) \\ % mysql -s -r mysql> SELECT CHAR(92); CHAR(92) \ --reconnect If the connection to the server is lost, automatically try to reconnect. A single reconnect attempt is made each time the connection is lost. Enabled by default, to disable use --skip-reconnect or --disable-reconnect. --safe-updates, --i-am-a-dummy, -U Allow only those UPDATE and DELETE statements that specify which rows to modify by using key values. If you have set this option in an option file, you can override it by using --safe-updates on the command line. See the section called MYSQL TIPS, for more information about this option. --secure-auth Do not send passwords to the server in old (pre-4.1.1) format. This prevents connections except for servers that use the newer password format. --select-limit=limit Set automatic limit for SELECT when using --safe-updates. (Default value is 1,000.) --server-arg=name Send name as a parameter to the embedded server. --show-warnings Cause warnings to be shown after each statement if there are any. This option applies to interactive and batch mode. --sigint-ignore Ignore SIGINT signals (typically the result of typing Control-C). --silent, -s Silent mode. Produce less output. This option can be given multiple times to produce less and less output. This option results in nontabular output format and escaping of special characters. Escaping may be disabled by using raw mode; see the description for the --raw option. --skip-auto-rehash Disable automatic rehashing. Synonym for --disable-auto-rehash. --skip-column-names, -N Do not write column names in results. --skip-line-numbers, -L Do not write line numbers for errors. Useful when you want to compare result files that include error messages. --socket=path, -S path For connections to localhost, the Unix socket file to use, or, on Windows, the name of the named pipe to use. Forces --protocol=socket when specified on the command line without other connection properties; on Windows, forces --protocol=pipe. --ssl Enable SSL for connection (automatically enabled with other flags). Disable with --skip-ssl. --ssl-ca=name CA file in PEM format (check OpenSSL docs, implies --ssl). --ssl-capath=name CA directory (check OpenSSL docs, implies --ssl). --ssl-cert=name X509 cert in PEM format (check OpenSSL docs, implies --ssl). --ssl-cipher=name SSL cipher to use (check OpenSSL docs, implies --ssl). --ssl-key=name X509 key in PEM format (check OpenSSL docs, implies --ssl). --ssl-crl=name Certificate revocation list (check OpenSSL docs, implies --ssl). --ssl-crlpath=name Certificate revocation list path (check OpenSSL docs, implies --ssl). --ssl-verify-server-cert Verify server's "Common Name" in its cert against hostname used when connecting. This option is disabled by default. --table, -t Display output in table format. This is the default for interactive use, but can be used to produce table output in batch mode. --tee=file_name Append a copy of output to the given file. This option works only in interactive mode. the section called MYSQL COMMANDS, discusses tee files further. --unbuffered, -n Flush the buffer after each query. --user=user_name, -u user_name The MariaDB user name to use when connecting to the server. --verbose, -v Verbose mode. Produce more output about what the program does. This option can be given multiple times to produce more and more output. (For example, -v -v -v produces table output format even in batch mode.) --version, -V Display version information and exit. --vertical, -E Print query output rows vertically (one line per column value). Without this option, you can specify vertical output for individual statements by terminating them with \G. --wait, -w If the connection cannot be established, wait and retry instead of aborting. --xml, -X Produce XML output. The output when --xml is used with mysql matches that of mysqldump --xml. See mysqldump(1) for details. The XML output also uses an XML namespace, as shown here: shell> mysql --xml -uroot -e "SHOW VARIABLES LIKE version%" <?xml version="1.0"?> <resultset statement="SHOW VARIABLES LIKE version%" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <row> <field name="Variable_name">version</field> <field name="Value">5.0.40-debug</field> </row> <row> <field name="Variable_name">version_comment</field> <field name="Value">Source distribution</field> </row> <row> <field name="Variable_name">version_compile_machine</field> <field name="Value">i686</field> </row> <row> <field name="Variable_name">version_compile_os</field> <field name="Value">suse-linux-gnu</field> </row> </resultset> You can also set the following variables by using --var_name=value. connect_timeout The number of seconds before connection timeout. (Default value is 0.) max_allowed_packet The maximum packet length to send to or receive from the server. (Default value is 16MB.) max_join_size The automatic limit for rows in a join when using --safe-updates. (Default value is 1,000,000.) net_buffer_length The buffer size for TCP/IP and socket communication. (Default value is 16KB.) select_limit The automatic limit for SELECT statements when using --safe-updates. (Default value is 1,000.) On Unix, the mysql client writes a record of executed statements to a history file. By default, this file is named .mysql_history and is created in your home directory. To specify a different file, set the value of the MYSQL_HISTFILE environment variable. The .mysql_history should be protected with a restrictive access mode because sensitive information might be written to it, such as the text of SQL statements that contain passwords. If you do not want to maintain a history file, first remove .mysql_history if it exists, and then use either of the following techniques: Set the MYSQL_HISTFILE variable to /dev/null. To cause this setting to take effect each time you log in, put the setting in one of your shells startup files. Create .mysql_history as a symbolic link to /dev/null: shell> ln -s /dev/null $HOME/.mysql_history You need do this only once. MYSQL COMMANDS top mysql sends each SQL statement that you issue to the server to be executed. There is also a set of commands that mysql itself interprets. For a list of these commands, type help or \h at the mysql> prompt: mysql> help List of all MySQL commands: Note that all text commands must be first on line and end with ; ? (\?) Synonym for `help. clear (\c) Clear command. connect (\r) Reconnect to the server. Optional arguments are db and host. delimiter (\d) Set statement delimiter. edit (\e) Edit command with $EDITOR. ego (\G) Send command to mysql server, display result vertically. exit (\q) Exit mysql. Same as quit. go (\g) Send command to mysql server. help (\h) Display this help. nopager (\n) Disable pager, print to stdout. notee (\t) Dont write into outfile. pager (\P) Set PAGER [to_pager]. Print the query results via PAGER. print (\p) Print current command. prompt (\R) Change your mysql prompt. quit (\q) Quit mysql. rehash (\#) Rebuild completion hash. source (\.) Execute an SQL script file. Takes a file name as an argument. status (\s) Get status information from the server. system (\!) Execute a system shell command. tee (\T) Set outfile [to_outfile]. Append everything into given outfile. use (\u) Use another database. Takes database name as argument. charset (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets. warnings (\W) Show warnings after every statement. nowarning (\w) Dont show warnings after every statement. For server side help, type help contents Each command has both a long and short form. The long form is not case sensitive; the short form is. The long form can be followed by an optional semicolon terminator, but the short form should not. The use of short-form commands within multi-line /* ... */ comments is not supported. help [arg], \h [arg], \? [arg], ? [arg] Display a help message listing the available mysql commands. If you provide an argument to the help command, mysql uses it as a search string to access server-side help. For more information, see the section called MYSQL SERVER-SIDE HELP. charset charset_name, \C charset_name Change the default character set and issue a SET NAMES statement. This enables the character set to remain synchronized on the client and server if mysql is run with auto-reconnect enabled (which is not recommended), because the specified character set is used for reconnects. clear, \c Clear the current input. Use this if you change your mind about executing the statement that you are entering. connect [db_name host_name]], \r [db_name host_name]] Reconnect to the server. The optional database name and host name arguments may be given to specify the default database or the host where the server is running. If omitted, the current values are used. delimiter str, \d str Change the string that mysql interprets as the separator between SQL statements. The default is the semicolon character (;). The delimiter can be specified as an unquoted or quoted argument. Quoting can be done with either single quote () or douple quote (") characters. To include a quote within a quoted string, either quote the string with the other quote character or escape the quote with a backslash (\) character. Backslash should be avoided outside of quoted strings because it is the escape character for MariaDB. For an unquoted argument, the delmiter is read up to the first space or end of line. For a quoted argument, the delimiter is read up to the matching quote on the line. When the delimiter recognized by mysql is set to something other than the default of ;, instances of that character are sent to the server without interpretation. However, the server itself still interprets ; as a statement delimiter and processes statements accordingly. This behavior on the server side comes into play for multiple-statement execution, and for parsing the body of stored procedures and functions, triggers, and events. edit, \e Edit the current input statement. mysql checks the values of the EDITOR and VISUAL environment variables to determine which editor to use. The default editor is vi if neither variable is set. The edit command works only in Unix. ego, \G Send the current statement to the server to be executed and display the result using vertical format. exit, \q Exit mysql. go, \g Send the current statement to the server to be executed. nopager, \n Disable output paging. See the description for pager. The nopager command works only in Unix. notee, \t Disable output copying to the tee file. See the description for tee. nowarning, \w Enable display of warnings after each statement. pager [command], \P [command] Enable output paging. By using the --pager option when you invoke mysql, it is possible to browse or search query results in interactive mode with Unix programs such as less, more, or any other similar program. If you specify no value for the option, mysql checks the value of the PAGER environment variable and sets the pager to that. Pager functionality works only in interactive mode. Output paging can be enabled interactively with the pager command and disabled with nopager. The command takes an optional argument; if given, the paging program is set to that. With no argument, the pager is set to the pager that was set on the command line, or stdout if no pager was specified. Output paging works only in Unix because it uses the popen() function, which does not exist on Windows. For Windows, the tee option can be used instead to save query output, although it is not as convenient as pager for browsing output in some situations. print, \p Print the current input statement without executing it. prompt [str], \R [str] Reconfigure the mysql prompt to the given string. The special character sequences that can be used in the prompt are described later in this section. If you specify the prompt command with no argument, mysql resets the prompt to the default of mysql>. quit, \q Exit mysql. rehash, \# Rebuild the completion hash that enables database, table, and column name completion while you are entering statements. (See the description for the --auto-rehash option.) source file_name, \. file_name Read the named file and executes the statements contained therein. On Windows, you can specify path name separators as / or \\. status, \s Provide status information about the connection and the server you are using. If you are running in --safe-updates mode, status also prints the values for the mysql variables that affect your queries. system command, \! command Execute the given command using your default command interpreter. The system command works only in Unix. tee [file_name], \T [file_name] By using the --tee option when you invoke mysql, you can log statements and their output. All the data displayed on the screen is appended into a given file. This can be very useful for debugging purposes also. mysql flushes results to the file after each statement, just before it prints its next prompt. Tee functionality works only in interactive mode. You can enable this feature interactively with the tee command. Without a parameter, the previous file is used. The tee file can be disabled with the notee command. Executing tee again re-enables logging. use db_name, \u db_name Use db_name as the default database. warnings, \W Enable display of warnings after each statement (if there are any). Here are a few tips about the pager command: You can use it to write to a file and the results go only to the file: mysql> pager cat > /tmp/log.txt You can also pass any options for the program that you want to use as your pager: mysql> pager less -n -i -S In the preceding example, note the -S option. You may find it very useful for browsing wide query results. Sometimes a very wide result set is difficult to read on the screen. The -S option to less can make the result set much more readable because you can scroll it horizontally using the left-arrow and right-arrow keys. You can also use -S interactively within less to switch the horizontal-browse mode on and off. For more information, read the less manual page: shell> man less The -F and -X options may be used with less to cause it to exit if output fits on one screen, which is convenient when no scrolling is necessary: mysql> pager less -n -i -S -F -X You can specify very complex pager commands for handling query output: mysql> pager cat | tee /dr1/tmp/res.txt \ | tee /dr2/tmp/res2.txt | less -n -i -S In this example, the command would send query results to two files in two different directories on two different file systems mounted on /dr1 and /dr2, yet still display the results onscreen via less. You can also combine the tee and pager functions. Have a tee file enabled and pager set to less, and you are able to browse the results using the less program and still have everything appended into a file the same time. The difference between the Unix tee used with the pager command and the mysql built-in tee command is that the built-in tee works even if you do not have the Unix tee available. The built-in tee also logs everything that is printed on the screen, whereas the Unix tee used with pager does not log quite that much. Additionally, tee file logging can be turned on and off interactively from within mysql. This is useful when you want to log some queries to a file, but not others. The prompt command reconfigures the default mysql> prompt. The string for defining the prompt can contain the following special sequences. Option Description \c A counter that increments for each statement you issue \D The full current date \d The default database \h The server host \l The current delimiter (new in 5.1.12) \m Minutes of the current time \n A newline character \O The current month in three-letter format (Jan, Feb, ...) \o The current month in numeric format \P am/pm \p The current TCP/IP port or socket file \R The current time, in 24-hour military time (023) \r The current time, standard 12-hour time (112) \S Semicolon \s Seconds of the current time \t A tab character \U Your full user_name@host_name account name \u Your user name \v The server version \w The current day of the week in three-letter format (Mon, Tue, ...) \Y The current year, four digits \y The current year, two digits \_ A space \ A space (a space follows the backslash) \ Single quote \" Double quote \\ A literal \ backslash character \x x, for any x not listed above You can set the prompt in several ways: Use an environment variable. You can set the MYSQL_PS1 environment variable to a prompt string. For example: shell> export MYSQL_PS1="(\u@\h) [\d]> " Use a command-line option. You can set the --prompt option on the command line to mysql. For example: shell> mysql --prompt="(\u@\h) [\d]> " (user@host) [database]> Use an option file. You can set the prompt option in the [mysql] group of any MariaDB option file, such as /etc/my.cnf or the .my.cnf file in your home directory. For example: [mysql] prompt=(\\u@\\h) [\\d]>\\_ In this example, note that the backslashes are doubled. If you set the prompt using the prompt option in an option file, it is advisable to double the backslashes when using the special prompt options. There is some overlap in the set of allowable prompt options and the set of special escape sequences that are recognized in option files. The overlap may cause you problems if you use single backslashes. For example, \s is interpreted as a space rather than as the current seconds value. The following example shows how to define a prompt within an option file to include the current time in HH:MM:SS> format: [mysql] prompt="\\r:\\m:\\s> " Set the prompt interactively. You can change your prompt interactively by using the prompt (or \R) command. For example: mysql> prompt (\u@\h) [\d]>\_ PROMPT set to (\u@\h) [\d]>\_ (user@host) [database]> (user@host) [database]> prompt Returning to default PROMPT of mysql> mysql> MYSQL SERVER-SIDE HELP top mysql> help search_string If you provide an argument to the help command, mysql uses it as a search string to access server-side help. The proper operation of this command requires that the help tables in the mysql database be initialized with help topic information. If there is no match for the search string, the search fails: mysql> help me Nothing found Please try to run help contents for a list of all accessible topics Use help contents to see a list of the help categories: mysql> help contents You asked for help about help category: "Contents" For more information, type help <item>, where <item> is one of the following categories: Account Management Administration Data Definition Data Manipulation Data Types Functions Functions and Modifiers for Use with GROUP BY Geographic Features Language Structure Plugins Storage Engines Stored Routines Table Maintenance Transactions Triggers If the search string matches multiple items, mysql shows a list of matching topics: mysql> help logs Many help items for your request exist. To make a more specific request, please type help <item>, where <item> is one of the following topics: SHOW SHOW BINARY LOGS SHOW ENGINE SHOW LOGS Use a topic as the search string to see the help entry for that topic: mysql> help show binary logs Name: SHOW BINARY LOGS Description: Syntax: SHOW BINARY LOGS SHOW MASTER LOGS Lists the binary log files on the server. This statement is used as part of the procedure described in [purge-binary-logs], that shows how to determine which logs can be purged. mysql> SHOW BINARY LOGS; +---------------+-----------+ | Log_name | File_size | +---------------+-----------+ | binlog.000015 | 724935 | | binlog.000016 | 733481 | +---------------+-----------+ EXECUTING SQL STATEMENTS FROM A TEXT FILE top The mysql client typically is used interactively, like this: shell> mysql db_name However, it is also possible to put your SQL statements in a file and then tell mysql to read its input from that file. To do so, create a text file text_file that contains the statements you wish to execute. Then invoke mysql as shown here: shell> mysql db_name < text_file If you place a USE db_name statement as the first statement in the file, it is unnecessary to specify the database name on the command line: shell> mysql < text_file If you are already running mysql, you can execute an SQL script file using the source command or \. command: mysql> source file_name mysql> \. file_name Sometimes you may want your script to display progress information to the user. For this you can insert statements like this: SELECT <info_to_display> AS ; The statement shown outputs <info_to_display>. You can also invoke mysql with the --verbose option, which causes each statement to be displayed before the result that it produces. mysql ignores Unicode byte order mark (BOM) characters at the beginning of input files. Presence of a BOM does not cause mysql to change its default character set. To do that, invoke mysql with an option such as --default-character-set=utf8. MYSQL TIPS top This section describes some techniques that can help you use mysql more effectively. Displaying Query Results Vertically Some query results are much more readable when displayed vertically, instead of in the usual horizontal table format. Queries can be displayed vertically by terminating the query with \G instead of a semicolon. For example, longer text values that include newlines often are much easier to read with vertical output: mysql> SELECT * FROM mails WHERE LENGTH(txt) < 300 LIMIT 300,1\G *************************** 1. row *************************** msg_nro: 3068 date: 2000-03-01 23:29:50 time_zone: +0200 mail_from: Monty reply: monty@no.spam.com mail_to: "Thimble Smith" <tim@no.spam.com> sbj: UTF-8 txt: >>>>> "Thimble" == Thimble Smith writes: Thimble> Hi. I think this is a good idea. Is anyone familiar Thimble> with UTF-8 or Unicode? Otherwise, Ill put this on my Thimble> TODO list and see what happens. Yes, please do that. Regards, Monty file: inbox-jani-1 hash: 190402944 1 row in set (0.09 sec) Using the --safe-updates Option For beginners, a useful startup option is --safe-updates (or --i-am-a-dummy, which has the same effect). It is helpful for cases when you might have issued a DELETE FROM tbl_name statement but forgotten the WHERE clause. Normally, such a statement deletes all rows from the table. With --safe-updates, you can delete rows only by specifying the key values that identify them. This helps prevent accidents. When you use the --safe-updates option, mysql issues the following statement when it connects to the MariaDB server: SET sql_safe_updates=1, sql_select_limit=1000, sql_max_join_size=1000000; The SET statement has the following effects: You are not allowed to execute an UPDATE or DELETE statement unless you specify a key constraint in the WHERE clause or provide a LIMIT clause (or both). For example: UPDATE tbl_name SET not_key_column=val WHERE key_column=val; UPDATE tbl_name SET not_key_column=val LIMIT 1; The server limits all large SELECT results to 1,000 rows unless the statement includes a LIMIT clause. The server aborts multiple-table SELECT statements that probably need to examine more than 1,000,000 row combinations. To specify limits different from 1,000 and 1,000,000, you can override the defaults by using the --select-limit and --max-join-size options: shell> mysql --safe-updates --select-limit=500 --max-join-size=10000 Disabling mysql Auto-Reconnect If the mysql client loses its connection to the server while sending a statement, it immediately and automatically tries to reconnect once to the server and send the statement again. However, even if mysql succeeds in reconnecting, your first connection has ended and all your previous session objects and settings are lost: temporary tables, the autocommit mode, and user-defined and session variables. Also, any current transaction rolls back. This behavior may be dangerous for you, as in the following example where the server was shut down and restarted between the first and second statements without you knowing it: mysql> SET @a=1; Query OK, 0 rows affected (0.05 sec) mysql> INSERT INTO t VALUES(@a); ERROR 2006: MySQL server has gone away No connection. Trying to reconnect... Connection id: 1 Current database: test Query OK, 1 row affected (1.30 sec) mysql> SELECT * FROM t; +------+ | a | +------+ | NULL | +------+ 1 row in set (0.05 sec) The @a user variable has been lost with the connection, and after the reconnection it is undefined. If it is important to have mysql terminate with an error if the connection has been lost, you can start the mysql client with the --skip-reconnect option. COPYRIGHT top Copyright 2007-2008 MySQL AB, 2008-2010 Sun Microsystems, Inc., 2010-2020 MariaDB Foundation This documentation is free software; you can redistribute it and/or modify it only under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This documentation is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA or see http://www.gnu.org/licenses/. NOTES top 1. Bug#25946 http://bugs.mysql.com/bug.php?id=25946 SEE ALSO top For more information, please refer to the MariaDB Knowledge Base, available online at https://mariadb.com/kb/ AUTHOR top MariaDB Foundation (http://www.mariadb.org/). COLOPHON top This page is part of the MariaDB (MariaDB database server) project. Information about the project can be found at http://mariadb.org/. If you have a bug report for this manual page, see https://mariadb.com/kb/en/mariadb/reporting-bugs/. This page was obtained from the project's upstream Git repository https://github.com/MariaDB/server on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-05-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org MariaDB 10.8 15 May 2020 MARIADB(1) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word "mysql" in all the files in the current containing the word "notes" in their name Bash Command:<START>find . -iname "*notes*" | xargs grep -i mysql<END>
search for the word "mysql" in all the files in the current containing the word "notes" in their name. print0 is used to handle files with newlines in their names or those which have only spaces in their names
find . -iname "*notes*" -print0 | xargs -I{} -0 grep -i mysql "{}"
['find', 'xargs', 'mysql', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word "mysql" in all the files in the current containing the word "notes" in their name. print0 is used to handle files with newlines in their names or those which have only spaces in their names Bash Command:<START>find . -iname "*notes*" -print0 | xargs -I{} -0 grep -i mysql "{}"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # mysql\n\n> The MySQL command-line tool.\n> More information: <https://www.mysql.com/>.\n\n- Connect to a database:\n\n`mysql {{database_name}}`\n\n- Connect to a database, user will be prompted for a password:\n\n`mysql -u {{user}} --password {{database_name}}`\n\n- Connect to a database on another host:\n\n`mysql -h {{database_host}} {{database_name}}`\n\n- Connect to a database through a Unix socket:\n\n`mysql --socket {{path/to/socket.sock}}`\n\n- Execute SQL statements in a script file (batch file):\n\n`mysql -e "source {{filename.sql}}" {{database_name}}`\n\n- Restore a database from a backup created with `mysqldump` (user will be prompted for a password):\n\n`mysql --user {{user}} --password {{database_name}} < {{path/to/backup.sql}}`\n\n- Restore all databases from a backup (user will be prompted for a password):\n\n`mysql --user {{user}} --password < {{path/to/backup.sql}}`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word "mysql" in all the files in the current containing the word "notes" in their name. print0 is used to handle files with newlines in their names or those which have only spaces in their names Bash Command:<START>find . -iname "*notes*" -print0 | xargs -I{} -0 grep -i mysql "{}"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. mysql(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training mysql(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | MYSQL OPTIONS | MYSQL COMMANDS | MYSQL SERVER-SIDE HELP | EXECUTING SQL STATEMENTS FROM A TEXT FILE | MYSQL TIPS | COPYRIGHT | NOTES | SEE ALSO | AUTHOR | COLOPHON MARIADB(1) MariaDB Database System MARIADB(1) NAME top mariadb - the MariaDB command-line tool (mysql is now a symlink to mariadb) SYNOPSIS top mysql [options] db_name DESCRIPTION top mysql is a simple SQL shell (with GNU readline capabilities). It supports interactive and non-interactive use. When used interactively, query results are presented in an ASCII-table format. When used non-interactively (for example, as a filter), the result is presented in tab-separated format. The output format can be changed using command options. If you have problems due to insufficient memory for large result sets, use the --quick option. This forces mysql to retrieve results from the server a row at a time rather than retrieving the entire result set and buffering it in memory before displaying it. This is done by returning the result set using the mysql_use_result() C API function in the client/server library rather than mysql_store_result(). Using mysql is very easy. Invoke it from the prompt of your command interpreter as follows: shell> mysql db_name Or: shell> mysql --user=user_name --password=your_password db_name Then type an SQL statement, end it with ;, \g, or \G and press Enter. Typing Control-C causes mysql to attempt to kill the current statement. If this cannot be done, or Control-C is typed again before the statement is killed, mysql exits. You can execute SQL statements in a script file (batch file) like this: shell> mysql db_name < script.sql > output.tab MYSQL OPTIONS top mysql supports the following options, which can be specified on the command line or in the [mysql], [client], [client-server] or [client-mariadb] option file groups. mysql also supports the options for processing option files. --help, -?, -I Display a help message and exit. --abort-source-on-error Abort 'source filename' operations in case of errors. --auto-rehash Enable automatic rehashing. This option is on by default, which enables database, table, and column name completion. Use --disable-auto-rehash, --no-auto-rehash, or --skip-auto-rehash to disable rehashing. That causes mysql to start faster, but you must issue the rehash command if you want to use name completion. To complete a name, enter the first part and press Tab. If the name is unambiguous, mysql completes it. Otherwise, you can press Tab again to see the possible names that begin with what you have typed so far. Completion does not occur if there is no default database. --auto-vertical-output Automatically switch to vertical output mode if the result is wider than the terminal width. --batch, -B Print results using tab as the column separator, with each row on a new line. With this option, mysql does not use the history file. Batch mode results in nontabular output format and escaping of special characters. Escaping may be disabled by using raw mode; see the description for the --raw option. --binary-mode Binary mode allows certain character sequences to be processed as data that would otherwise be treated with a special meaning by the parser. Specifically, this switch turns off parsing of all client commands except \C and DELIMITER in non-interactive mode (i.e., when binary mode is combined with either 1) piped input, 2) the --batch mysql option, or 3) the 'source' command). Also, in binary mode, occurrences of '\r\n' and ASCII '\0' are preserved within strings, whereas by default, '\r\n' is translated to '\n' and '\0' is disallowed in user input. --character-sets-dir=path The directory where character sets are installed. --column-names Write column names in results. --column-type-info, -m Display result set metadata. --comments, -c Whether to preserve comments in statements sent to the server. The default is --skip-comments (discard comments), enable with --comments (preserve comments). --compress, -C Compress all information sent between the client and the server if both support compression. --connect-timeout=seconds Set the number of seconds before connection timeout. (Default value is 0.) --database=db_name, -D db_name The database to use. --debug[=debug_options], -# [debug_options] Write a debugging log. A typical debug_options string is d:t:o,file_name. The default is d:t:o,/tmp/mysql.trace. --debug-check Print some debugging information when the program exits. --debug-info, -T Prints debugging information and memory and CPU usage statistics when the program exits. --default-auth=name Default authentication client-side plugin to use. --default-character-set=charset_name Use charset_name as the default character set for the client and connection. A common issue that can occur when the operating system uses utf8 or another multi-byte character set is that output from the mysql client is formatted incorrectly, due to the fact that the MariaDB client uses the latin1 character set by default. You can usually fix such issues by using this option to force the client to use the system character set instead. --defaults-extra-file=filename Set filename as the file to read default options from after the global defaults files has been read. Must be given as first option. --defaults-file=filename Set filename as the file to read default options from, override global defaults files. Must be given as first option. --defaults-group-suffix=suffix In addition to the groups named on the command line, read groups that have the given suffix. --delimiter=str Set the statement delimiter. The default is the semicolon character (;). --disable-named-commands Disable named commands. Use the \* form only, or use named commands only at the beginning of a line ending with a semicolon (;). mysql starts with this option enabled by default. However, even with this option, long-format commands still work from the first line. See the section called MYSQL COMMANDS. --enable-cleartext-plugin Obsolete option. Exists only for MySQL compatibility. --execute=statement, -e statement Execute the statement and quit. Disables --force and history file. The default output format is like that produced with --batch. --force, -f Continue even if an SQL error occurs. Sets --abort-source-on- error to 0. --host=host_name, -h host_name Connect to the MariaDB server on the given host. --html, -H Produce HTML output. --ignore-spaces, -i Ignore spaces after function names. Allows one to have spaces (including tab characters and new line characters) between function name and '('. The drawback is that this causes built in functions to become reserved words. --init-command=str SQL Command to execute when connecting to the MariaDB server. Will automatically be re-executed when reconnecting. --line-numbers Write line numbers for errors. Disable this with --skip-line-numbers. --local-infile[={0|1}] Enable or disable LOCAL capability for LOAD DATA INFILE. With no value, the option enables LOCAL. The option may be given as --local-infile=0 or --local-infile=1 to explicitly disable or enable LOCAL. Enabling LOCAL has no effect if the server does not also support it. --max-allowed-packet=num Set the maximum packet length to send to or receive from the server. (Default value is 16MB, largest 1GB.) --max-join-size=num Set the automatic limit for rows in a join when using --safe-updates. (Default value is 1,000,000.) --named-commands, -G Enable named mysql commands. Long-format commands are allowed, not just short-format commands. For example, quit and \q both are recognized. Use --skip-named-commands to disable named commands. See the section called MYSQL COMMANDS. Disabled by default.  --net-buffer-length=size Set the buffer size for TCP/IP and socket communication. (Default value is 16KB.) --no-auto-rehash, -A This has the same effect as --skip-auto-rehash. See the description for --auto-rehash. --no-beep, -b Do not beep when errors occur. --no-defaults Do not read default options from any option file. This must be given as the first argument. --one-database, -o Ignore statements except those those that occur while the default database is the one named on the command line. This filtering is limited, and based only on USE statements. This is useful for skipping updates to other databases in the binary log. --pager[=command] Use the given command for paging query output. If the command is omitted, the default pager is the value of your PAGER environment variable. Valid pagers are less, more, cat [> filename], and so forth. This option works only on Unix and only in interactive mode. To disable paging, use --skip-pager. the section called MYSQL COMMANDS, discusses output paging further. --password[=password], -p[password] The password to use when connecting to the server. If you use the short option form (-p), you cannot have a space between the option and the password. If you omit the password value following the --password or -p option on the command line, mysql prompts for one. Specifying a password on the command line should be considered insecure. You can use an option file to avoid giving the password on the command line. --pipe, -W On Windows, connect to the server via a named pipe. This option applies only if the server supports named-pipe connections. --plugin-dir=dir_name Directory for client-side plugins. --port=port_num, -P port_num The TCP/IP port number to use for the connection or 0 for default to, in order of preference, my.cnf, $MYSQL_TCP_PORT, /etc/services, built-in default (3306). Forces --protocol=tcp when specified on the command line without other connection properties. --print-defaults Print the program argument list and exit. This must be given as the first argument. --progress-reports Get progress reports for long running commands (such as ALTER TABLE). (Defaults to on; use --skip-progress-reports to disable.) --prompt=format_str Set the prompt to the specified format. The special sequences that the prompt can contain are described in the section called MYSQL COMMANDS. --protocol={TCP|SOCKET|PIPE|MEMORY} The connection protocol to use for connecting to the server. It is useful when the other connection parameters normally would cause a protocol to be used other than the one you want. --quick, -q Do not cache each query result, print each row as it is received. This may slow down the server if the output is suspended. With this option, mysql does not use the history file. --raw, -r For tabular output, the boxing around columns enables one column value to be distinguished from another. For nontabular output (such as is produced in batch mode or when the --batch or --silent option is given), special characters are escaped in the output so they can be identified easily. Newline, tab, NUL, and backslash are written as \n, \t, \0, and \\. The --raw option disables this character escaping. The following example demonstrates tabular versus nontabular output and the use of raw mode to disable escaping: % mysql mysql> SELECT CHAR(92); +----------+ | CHAR(92) | +----------+ | \ | +----------+ % mysql -s mysql> SELECT CHAR(92); CHAR(92) \\ % mysql -s -r mysql> SELECT CHAR(92); CHAR(92) \ --reconnect If the connection to the server is lost, automatically try to reconnect. A single reconnect attempt is made each time the connection is lost. Enabled by default, to disable use --skip-reconnect or --disable-reconnect. --safe-updates, --i-am-a-dummy, -U Allow only those UPDATE and DELETE statements that specify which rows to modify by using key values. If you have set this option in an option file, you can override it by using --safe-updates on the command line. See the section called MYSQL TIPS, for more information about this option. --secure-auth Do not send passwords to the server in old (pre-4.1.1) format. This prevents connections except for servers that use the newer password format. --select-limit=limit Set automatic limit for SELECT when using --safe-updates. (Default value is 1,000.) --server-arg=name Send name as a parameter to the embedded server. --show-warnings Cause warnings to be shown after each statement if there are any. This option applies to interactive and batch mode. --sigint-ignore Ignore SIGINT signals (typically the result of typing Control-C). --silent, -s Silent mode. Produce less output. This option can be given multiple times to produce less and less output. This option results in nontabular output format and escaping of special characters. Escaping may be disabled by using raw mode; see the description for the --raw option. --skip-auto-rehash Disable automatic rehashing. Synonym for --disable-auto-rehash. --skip-column-names, -N Do not write column names in results. --skip-line-numbers, -L Do not write line numbers for errors. Useful when you want to compare result files that include error messages. --socket=path, -S path For connections to localhost, the Unix socket file to use, or, on Windows, the name of the named pipe to use. Forces --protocol=socket when specified on the command line without other connection properties; on Windows, forces --protocol=pipe. --ssl Enable SSL for connection (automatically enabled with other flags). Disable with --skip-ssl. --ssl-ca=name CA file in PEM format (check OpenSSL docs, implies --ssl). --ssl-capath=name CA directory (check OpenSSL docs, implies --ssl). --ssl-cert=name X509 cert in PEM format (check OpenSSL docs, implies --ssl). --ssl-cipher=name SSL cipher to use (check OpenSSL docs, implies --ssl). --ssl-key=name X509 key in PEM format (check OpenSSL docs, implies --ssl). --ssl-crl=name Certificate revocation list (check OpenSSL docs, implies --ssl). --ssl-crlpath=name Certificate revocation list path (check OpenSSL docs, implies --ssl). --ssl-verify-server-cert Verify server's "Common Name" in its cert against hostname used when connecting. This option is disabled by default. --table, -t Display output in table format. This is the default for interactive use, but can be used to produce table output in batch mode. --tee=file_name Append a copy of output to the given file. This option works only in interactive mode. the section called MYSQL COMMANDS, discusses tee files further. --unbuffered, -n Flush the buffer after each query. --user=user_name, -u user_name The MariaDB user name to use when connecting to the server. --verbose, -v Verbose mode. Produce more output about what the program does. This option can be given multiple times to produce more and more output. (For example, -v -v -v produces table output format even in batch mode.) --version, -V Display version information and exit. --vertical, -E Print query output rows vertically (one line per column value). Without this option, you can specify vertical output for individual statements by terminating them with \G. --wait, -w If the connection cannot be established, wait and retry instead of aborting. --xml, -X Produce XML output. The output when --xml is used with mysql matches that of mysqldump --xml. See mysqldump(1) for details. The XML output also uses an XML namespace, as shown here: shell> mysql --xml -uroot -e "SHOW VARIABLES LIKE version%" <?xml version="1.0"?> <resultset statement="SHOW VARIABLES LIKE version%" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <row> <field name="Variable_name">version</field> <field name="Value">5.0.40-debug</field> </row> <row> <field name="Variable_name">version_comment</field> <field name="Value">Source distribution</field> </row> <row> <field name="Variable_name">version_compile_machine</field> <field name="Value">i686</field> </row> <row> <field name="Variable_name">version_compile_os</field> <field name="Value">suse-linux-gnu</field> </row> </resultset> You can also set the following variables by using --var_name=value. connect_timeout The number of seconds before connection timeout. (Default value is 0.) max_allowed_packet The maximum packet length to send to or receive from the server. (Default value is 16MB.) max_join_size The automatic limit for rows in a join when using --safe-updates. (Default value is 1,000,000.) net_buffer_length The buffer size for TCP/IP and socket communication. (Default value is 16KB.) select_limit The automatic limit for SELECT statements when using --safe-updates. (Default value is 1,000.) On Unix, the mysql client writes a record of executed statements to a history file. By default, this file is named .mysql_history and is created in your home directory. To specify a different file, set the value of the MYSQL_HISTFILE environment variable. The .mysql_history should be protected with a restrictive access mode because sensitive information might be written to it, such as the text of SQL statements that contain passwords. If you do not want to maintain a history file, first remove .mysql_history if it exists, and then use either of the following techniques: Set the MYSQL_HISTFILE variable to /dev/null. To cause this setting to take effect each time you log in, put the setting in one of your shells startup files. Create .mysql_history as a symbolic link to /dev/null: shell> ln -s /dev/null $HOME/.mysql_history You need do this only once. MYSQL COMMANDS top mysql sends each SQL statement that you issue to the server to be executed. There is also a set of commands that mysql itself interprets. For a list of these commands, type help or \h at the mysql> prompt: mysql> help List of all MySQL commands: Note that all text commands must be first on line and end with ; ? (\?) Synonym for `help. clear (\c) Clear command. connect (\r) Reconnect to the server. Optional arguments are db and host. delimiter (\d) Set statement delimiter. edit (\e) Edit command with $EDITOR. ego (\G) Send command to mysql server, display result vertically. exit (\q) Exit mysql. Same as quit. go (\g) Send command to mysql server. help (\h) Display this help. nopager (\n) Disable pager, print to stdout. notee (\t) Dont write into outfile. pager (\P) Set PAGER [to_pager]. Print the query results via PAGER. print (\p) Print current command. prompt (\R) Change your mysql prompt. quit (\q) Quit mysql. rehash (\#) Rebuild completion hash. source (\.) Execute an SQL script file. Takes a file name as an argument. status (\s) Get status information from the server. system (\!) Execute a system shell command. tee (\T) Set outfile [to_outfile]. Append everything into given outfile. use (\u) Use another database. Takes database name as argument. charset (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets. warnings (\W) Show warnings after every statement. nowarning (\w) Dont show warnings after every statement. For server side help, type help contents Each command has both a long and short form. The long form is not case sensitive; the short form is. The long form can be followed by an optional semicolon terminator, but the short form should not. The use of short-form commands within multi-line /* ... */ comments is not supported. help [arg], \h [arg], \? [arg], ? [arg] Display a help message listing the available mysql commands. If you provide an argument to the help command, mysql uses it as a search string to access server-side help. For more information, see the section called MYSQL SERVER-SIDE HELP. charset charset_name, \C charset_name Change the default character set and issue a SET NAMES statement. This enables the character set to remain synchronized on the client and server if mysql is run with auto-reconnect enabled (which is not recommended), because the specified character set is used for reconnects. clear, \c Clear the current input. Use this if you change your mind about executing the statement that you are entering. connect [db_name host_name]], \r [db_name host_name]] Reconnect to the server. The optional database name and host name arguments may be given to specify the default database or the host where the server is running. If omitted, the current values are used. delimiter str, \d str Change the string that mysql interprets as the separator between SQL statements. The default is the semicolon character (;). The delimiter can be specified as an unquoted or quoted argument. Quoting can be done with either single quote () or douple quote (") characters. To include a quote within a quoted string, either quote the string with the other quote character or escape the quote with a backslash (\) character. Backslash should be avoided outside of quoted strings because it is the escape character for MariaDB. For an unquoted argument, the delmiter is read up to the first space or end of line. For a quoted argument, the delimiter is read up to the matching quote on the line. When the delimiter recognized by mysql is set to something other than the default of ;, instances of that character are sent to the server without interpretation. However, the server itself still interprets ; as a statement delimiter and processes statements accordingly. This behavior on the server side comes into play for multiple-statement execution, and for parsing the body of stored procedures and functions, triggers, and events. edit, \e Edit the current input statement. mysql checks the values of the EDITOR and VISUAL environment variables to determine which editor to use. The default editor is vi if neither variable is set. The edit command works only in Unix. ego, \G Send the current statement to the server to be executed and display the result using vertical format. exit, \q Exit mysql. go, \g Send the current statement to the server to be executed. nopager, \n Disable output paging. See the description for pager. The nopager command works only in Unix. notee, \t Disable output copying to the tee file. See the description for tee. nowarning, \w Enable display of warnings after each statement. pager [command], \P [command] Enable output paging. By using the --pager option when you invoke mysql, it is possible to browse or search query results in interactive mode with Unix programs such as less, more, or any other similar program. If you specify no value for the option, mysql checks the value of the PAGER environment variable and sets the pager to that. Pager functionality works only in interactive mode. Output paging can be enabled interactively with the pager command and disabled with nopager. The command takes an optional argument; if given, the paging program is set to that. With no argument, the pager is set to the pager that was set on the command line, or stdout if no pager was specified. Output paging works only in Unix because it uses the popen() function, which does not exist on Windows. For Windows, the tee option can be used instead to save query output, although it is not as convenient as pager for browsing output in some situations. print, \p Print the current input statement without executing it. prompt [str], \R [str] Reconfigure the mysql prompt to the given string. The special character sequences that can be used in the prompt are described later in this section. If you specify the prompt command with no argument, mysql resets the prompt to the default of mysql>. quit, \q Exit mysql. rehash, \# Rebuild the completion hash that enables database, table, and column name completion while you are entering statements. (See the description for the --auto-rehash option.) source file_name, \. file_name Read the named file and executes the statements contained therein. On Windows, you can specify path name separators as / or \\. status, \s Provide status information about the connection and the server you are using. If you are running in --safe-updates mode, status also prints the values for the mysql variables that affect your queries. system command, \! command Execute the given command using your default command interpreter. The system command works only in Unix. tee [file_name], \T [file_name] By using the --tee option when you invoke mysql, you can log statements and their output. All the data displayed on the screen is appended into a given file. This can be very useful for debugging purposes also. mysql flushes results to the file after each statement, just before it prints its next prompt. Tee functionality works only in interactive mode. You can enable this feature interactively with the tee command. Without a parameter, the previous file is used. The tee file can be disabled with the notee command. Executing tee again re-enables logging. use db_name, \u db_name Use db_name as the default database. warnings, \W Enable display of warnings after each statement (if there are any). Here are a few tips about the pager command: You can use it to write to a file and the results go only to the file: mysql> pager cat > /tmp/log.txt You can also pass any options for the program that you want to use as your pager: mysql> pager less -n -i -S In the preceding example, note the -S option. You may find it very useful for browsing wide query results. Sometimes a very wide result set is difficult to read on the screen. The -S option to less can make the result set much more readable because you can scroll it horizontally using the left-arrow and right-arrow keys. You can also use -S interactively within less to switch the horizontal-browse mode on and off. For more information, read the less manual page: shell> man less The -F and -X options may be used with less to cause it to exit if output fits on one screen, which is convenient when no scrolling is necessary: mysql> pager less -n -i -S -F -X You can specify very complex pager commands for handling query output: mysql> pager cat | tee /dr1/tmp/res.txt \ | tee /dr2/tmp/res2.txt | less -n -i -S In this example, the command would send query results to two files in two different directories on two different file systems mounted on /dr1 and /dr2, yet still display the results onscreen via less. You can also combine the tee and pager functions. Have a tee file enabled and pager set to less, and you are able to browse the results using the less program and still have everything appended into a file the same time. The difference between the Unix tee used with the pager command and the mysql built-in tee command is that the built-in tee works even if you do not have the Unix tee available. The built-in tee also logs everything that is printed on the screen, whereas the Unix tee used with pager does not log quite that much. Additionally, tee file logging can be turned on and off interactively from within mysql. This is useful when you want to log some queries to a file, but not others. The prompt command reconfigures the default mysql> prompt. The string for defining the prompt can contain the following special sequences. Option Description \c A counter that increments for each statement you issue \D The full current date \d The default database \h The server host \l The current delimiter (new in 5.1.12) \m Minutes of the current time \n A newline character \O The current month in three-letter format (Jan, Feb, ...) \o The current month in numeric format \P am/pm \p The current TCP/IP port or socket file \R The current time, in 24-hour military time (023) \r The current time, standard 12-hour time (112) \S Semicolon \s Seconds of the current time \t A tab character \U Your full user_name@host_name account name \u Your user name \v The server version \w The current day of the week in three-letter format (Mon, Tue, ...) \Y The current year, four digits \y The current year, two digits \_ A space \ A space (a space follows the backslash) \ Single quote \" Double quote \\ A literal \ backslash character \x x, for any x not listed above You can set the prompt in several ways: Use an environment variable. You can set the MYSQL_PS1 environment variable to a prompt string. For example: shell> export MYSQL_PS1="(\u@\h) [\d]> " Use a command-line option. You can set the --prompt option on the command line to mysql. For example: shell> mysql --prompt="(\u@\h) [\d]> " (user@host) [database]> Use an option file. You can set the prompt option in the [mysql] group of any MariaDB option file, such as /etc/my.cnf or the .my.cnf file in your home directory. For example: [mysql] prompt=(\\u@\\h) [\\d]>\\_ In this example, note that the backslashes are doubled. If you set the prompt using the prompt option in an option file, it is advisable to double the backslashes when using the special prompt options. There is some overlap in the set of allowable prompt options and the set of special escape sequences that are recognized in option files. The overlap may cause you problems if you use single backslashes. For example, \s is interpreted as a space rather than as the current seconds value. The following example shows how to define a prompt within an option file to include the current time in HH:MM:SS> format: [mysql] prompt="\\r:\\m:\\s> " Set the prompt interactively. You can change your prompt interactively by using the prompt (or \R) command. For example: mysql> prompt (\u@\h) [\d]>\_ PROMPT set to (\u@\h) [\d]>\_ (user@host) [database]> (user@host) [database]> prompt Returning to default PROMPT of mysql> mysql> MYSQL SERVER-SIDE HELP top mysql> help search_string If you provide an argument to the help command, mysql uses it as a search string to access server-side help. The proper operation of this command requires that the help tables in the mysql database be initialized with help topic information. If there is no match for the search string, the search fails: mysql> help me Nothing found Please try to run help contents for a list of all accessible topics Use help contents to see a list of the help categories: mysql> help contents You asked for help about help category: "Contents" For more information, type help <item>, where <item> is one of the following categories: Account Management Administration Data Definition Data Manipulation Data Types Functions Functions and Modifiers for Use with GROUP BY Geographic Features Language Structure Plugins Storage Engines Stored Routines Table Maintenance Transactions Triggers If the search string matches multiple items, mysql shows a list of matching topics: mysql> help logs Many help items for your request exist. To make a more specific request, please type help <item>, where <item> is one of the following topics: SHOW SHOW BINARY LOGS SHOW ENGINE SHOW LOGS Use a topic as the search string to see the help entry for that topic: mysql> help show binary logs Name: SHOW BINARY LOGS Description: Syntax: SHOW BINARY LOGS SHOW MASTER LOGS Lists the binary log files on the server. This statement is used as part of the procedure described in [purge-binary-logs], that shows how to determine which logs can be purged. mysql> SHOW BINARY LOGS; +---------------+-----------+ | Log_name | File_size | +---------------+-----------+ | binlog.000015 | 724935 | | binlog.000016 | 733481 | +---------------+-----------+ EXECUTING SQL STATEMENTS FROM A TEXT FILE top The mysql client typically is used interactively, like this: shell> mysql db_name However, it is also possible to put your SQL statements in a file and then tell mysql to read its input from that file. To do so, create a text file text_file that contains the statements you wish to execute. Then invoke mysql as shown here: shell> mysql db_name < text_file If you place a USE db_name statement as the first statement in the file, it is unnecessary to specify the database name on the command line: shell> mysql < text_file If you are already running mysql, you can execute an SQL script file using the source command or \. command: mysql> source file_name mysql> \. file_name Sometimes you may want your script to display progress information to the user. For this you can insert statements like this: SELECT <info_to_display> AS ; The statement shown outputs <info_to_display>. You can also invoke mysql with the --verbose option, which causes each statement to be displayed before the result that it produces. mysql ignores Unicode byte order mark (BOM) characters at the beginning of input files. Presence of a BOM does not cause mysql to change its default character set. To do that, invoke mysql with an option such as --default-character-set=utf8. MYSQL TIPS top This section describes some techniques that can help you use mysql more effectively. Displaying Query Results Vertically Some query results are much more readable when displayed vertically, instead of in the usual horizontal table format. Queries can be displayed vertically by terminating the query with \G instead of a semicolon. For example, longer text values that include newlines often are much easier to read with vertical output: mysql> SELECT * FROM mails WHERE LENGTH(txt) < 300 LIMIT 300,1\G *************************** 1. row *************************** msg_nro: 3068 date: 2000-03-01 23:29:50 time_zone: +0200 mail_from: Monty reply: monty@no.spam.com mail_to: "Thimble Smith" <tim@no.spam.com> sbj: UTF-8 txt: >>>>> "Thimble" == Thimble Smith writes: Thimble> Hi. I think this is a good idea. Is anyone familiar Thimble> with UTF-8 or Unicode? Otherwise, Ill put this on my Thimble> TODO list and see what happens. Yes, please do that. Regards, Monty file: inbox-jani-1 hash: 190402944 1 row in set (0.09 sec) Using the --safe-updates Option For beginners, a useful startup option is --safe-updates (or --i-am-a-dummy, which has the same effect). It is helpful for cases when you might have issued a DELETE FROM tbl_name statement but forgotten the WHERE clause. Normally, such a statement deletes all rows from the table. With --safe-updates, you can delete rows only by specifying the key values that identify them. This helps prevent accidents. When you use the --safe-updates option, mysql issues the following statement when it connects to the MariaDB server: SET sql_safe_updates=1, sql_select_limit=1000, sql_max_join_size=1000000; The SET statement has the following effects: You are not allowed to execute an UPDATE or DELETE statement unless you specify a key constraint in the WHERE clause or provide a LIMIT clause (or both). For example: UPDATE tbl_name SET not_key_column=val WHERE key_column=val; UPDATE tbl_name SET not_key_column=val LIMIT 1; The server limits all large SELECT results to 1,000 rows unless the statement includes a LIMIT clause. The server aborts multiple-table SELECT statements that probably need to examine more than 1,000,000 row combinations. To specify limits different from 1,000 and 1,000,000, you can override the defaults by using the --select-limit and --max-join-size options: shell> mysql --safe-updates --select-limit=500 --max-join-size=10000 Disabling mysql Auto-Reconnect If the mysql client loses its connection to the server while sending a statement, it immediately and automatically tries to reconnect once to the server and send the statement again. However, even if mysql succeeds in reconnecting, your first connection has ended and all your previous session objects and settings are lost: temporary tables, the autocommit mode, and user-defined and session variables. Also, any current transaction rolls back. This behavior may be dangerous for you, as in the following example where the server was shut down and restarted between the first and second statements without you knowing it: mysql> SET @a=1; Query OK, 0 rows affected (0.05 sec) mysql> INSERT INTO t VALUES(@a); ERROR 2006: MySQL server has gone away No connection. Trying to reconnect... Connection id: 1 Current database: test Query OK, 1 row affected (1.30 sec) mysql> SELECT * FROM t; +------+ | a | +------+ | NULL | +------+ 1 row in set (0.05 sec) The @a user variable has been lost with the connection, and after the reconnection it is undefined. If it is important to have mysql terminate with an error if the connection has been lost, you can start the mysql client with the --skip-reconnect option. COPYRIGHT top Copyright 2007-2008 MySQL AB, 2008-2010 Sun Microsystems, Inc., 2010-2020 MariaDB Foundation This documentation is free software; you can redistribute it and/or modify it only under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This documentation is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA or see http://www.gnu.org/licenses/. NOTES top 1. Bug#25946 http://bugs.mysql.com/bug.php?id=25946 SEE ALSO top For more information, please refer to the MariaDB Knowledge Base, available online at https://mariadb.com/kb/ AUTHOR top MariaDB Foundation (http://www.mariadb.org/). COLOPHON top This page is part of the MariaDB (MariaDB database server) project. Information about the project can be found at http://mariadb.org/. If you have a bug report for this manual page, see https://mariadb.com/kb/en/mariadb/reporting-bugs/. This page was obtained from the project's upstream Git repository https://github.com/MariaDB/server on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-05-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org MariaDB 10.8 15 May 2020 MARIADB(1) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word "mysql" in all the files in the current containing the word "notes" in their name. print0 is used to handle files with newlines in their names or those which have only spaces in their names Bash Command:<START>find . -iname "*notes*" -print0 | xargs -I{} -0 grep -i mysql "{}"<END>
search for the word "nameserver" in all the configuration files of the /etc folder
find /etc/ -type f -name "*.conf" -print0 | xargs -I {} -0 grep "nameserver" "{}"
['find', 'xargs', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word "nameserver" in all the configuration files of the /etc folder Bash Command:<START>find /etc/ -type f -name "*.conf" -print0 | xargs -I {} -0 grep "nameserver" "{}"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word "nameserver" in all the configuration files of the /etc folder Bash Command:<START>find /etc/ -type f -name "*.conf" -print0 | xargs -I {} -0 grep "nameserver" "{}"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word "nameserver" in all the configuration files of the /etc folder Bash Command:<START>find /etc/ -type f -name "*.conf" -print0 | xargs -I {} -0 grep "nameserver" "{}"<END>
search for the word "nameserver" in all the regular/normal files in the /etc directory and display the name of the file along with the matched line
find /etc/ -iname "*" -type f -print0 | xargs -0 grep -H "nameserver"
['find', 'xargs', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word "nameserver" in all the regular/normal files in the /etc directory and display the name of the file along with the matched line Bash Command:<START>find /etc/ -iname "*" -type f -print0 | xargs -0 grep -H "nameserver"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word "nameserver" in all the regular/normal files in the /etc directory and display the name of the file along with the matched line Bash Command:<START>find /etc/ -iname "*" -type f -print0 | xargs -0 grep -H "nameserver"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word "nameserver" in all the regular/normal files in the /etc directory and display the name of the file along with the matched line Bash Command:<START>find /etc/ -iname "*" -type f -print0 | xargs -0 grep -H "nameserver"<END>
search for the word "nutshell" or "Nutshell" in all the files in the folder book
find /book -print | xargs grep '[Nn] utshell'
['find', 'xargs', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word "nutshell" or "Nutshell" in all the files in the folder book Bash Command:<START>find /book -print | xargs grep '[Nn] utshell'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word "nutshell" or "Nutshell" in all the files in the folder book Bash Command:<START>find /book -print | xargs grep '[Nn] utshell'<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word "nutshell" or "Nutshell" in all the files in the folder book Bash Command:<START>find /book -print | xargs grep '[Nn] utshell'<END>
search for the word "put" in all the files in the current folder which have the word "bills" in their name and display the matched line along with the filename.
find . -name '*bills*' -exec grep -H "put" {} \;
['find', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word "put" in all the files in the current folder which have the word "bills" in their name and display the matched line along with the filename. Bash Command:<START>find . -name '*bills*' -exec grep -H "put" {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word "put" in all the files in the current folder which have the word "bills" in their name and display the matched line along with the filename. Bash Command:<START>find . -name '*bills*' -exec grep -H "put" {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word "put" in all the files in the current folder which have the word "bills" in their name and display the matched line along with the filename. Bash Command:<START>find . -name '*bills*' -exec grep -H "put" {} \;<END>
search for the word "redeem reward" in all the regular/normal files in the current folder
find . -type f -exec grep -i “redeem reward” {} \; -print
['find', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word "redeem reward" in all the regular/normal files in the current folder Bash Command:<START>find . -type f -exec grep -i “redeem reward” {} \; -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word "redeem reward" in all the regular/normal files in the current folder Bash Command:<START>find . -type f -exec grep -i “redeem reward” {} \; -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word "redeem reward" in all the regular/normal files in the current folder Bash Command:<START>find . -type f -exec grep -i “redeem reward” {} \; -print<END>
search for the word "search-pattern" in all the regular/normal files in the current folder and display the matched file name
find . -type f | xargs grep -l "search-pattern"
['find', 'xargs', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word "search-pattern" in all the regular/normal files in the current folder and display the matched file name Bash Command:<START>find . -type f | xargs grep -l "search-pattern"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word "search-pattern" in all the regular/normal files in the current folder and display the matched file name Bash Command:<START>find . -type f | xargs grep -l "search-pattern"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word "search-pattern" in all the regular/normal files in the current folder and display the matched file name Bash Command:<START>find . -type f | xargs grep -l "search-pattern"<END>
search for the word "slrn" in all the files in the current folder
find ./ -exec grep -q 'slrn' '{}' \; -print
['find', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word "slrn" in all the files in the current folder Bash Command:<START>find ./ -exec grep -q 'slrn' '{}' \; -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word "slrn" in all the files in the current folder Bash Command:<START>find ./ -exec grep -q 'slrn' '{}' \; -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word "slrn" in all the files in the current folder Bash Command:<START>find ./ -exec grep -q 'slrn' '{}' \; -print<END>
search for the word "slrn" in all the files in the folder $HOME/html/andrews-corner
find $HOME/html/andrews-corner -exec grep -q 'slrn' '{}' \; -print
['find', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word "slrn" in all the files in the folder $HOME/html/andrews-corner Bash Command:<START>find $HOME/html/andrews-corner -exec grep -q 'slrn' '{}' \; -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word "slrn" in all the files in the folder $HOME/html/andrews-corner Bash Command:<START>find $HOME/html/andrews-corner -exec grep -q 'slrn' '{}' \; -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word "slrn" in all the files in the folder $HOME/html/andrews-corner Bash Command:<START>find $HOME/html/andrews-corner -exec grep -q 'slrn' '{}' \; -print<END>
search for the word LOG in all the files in the folder ~/jsmith
find ~jsmith -exec grep LOG '{}' /dev/null \; -print
['find', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word LOG in all the files in the folder ~/jsmith Bash Command:<START>find ~jsmith -exec grep LOG '{}' /dev/null \; -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word LOG in all the files in the folder ~/jsmith Bash Command:<START>find ~jsmith -exec grep LOG '{}' /dev/null \; -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word LOG in all the files in the folder ~/jsmith Bash Command:<START>find ~jsmith -exec grep LOG '{}' /dev/null \; -print<END>
search for the word bananas in the all the regular/normal files in the entire file system
find / -type f -exec grep bananas {} \; -print
['find', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word bananas in the all the regular/normal files in the entire file system Bash Command:<START>find / -type f -exec grep bananas {} \; -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word bananas in the all the regular/normal files in the entire file system Bash Command:<START>find / -type f -exec grep bananas {} \; -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word bananas in the all the regular/normal files in the entire file system Bash Command:<START>find / -type f -exec grep bananas {} \; -print<END>
search for the word echo all the bash files(files ending with .bash) in the current folder
find . -name "*.bash" |xargs grep "echo"
['find', 'xargs', 'grep', 'echo']
Output a Bash command to accomplish the following task. Task: search for the word echo all the bash files(files ending with .bash) in the current folder Bash Command:<START>find . -name "*.bash" |xargs grep "echo"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n # echo\n\n> Print given arguments.\n> More information: <https://www.gnu.org/software/coreutils/echo>.\n\n- Print a text message. Note: quotes are optional:\n\n`echo "{{Hello World}}"`\n\n- Print a message with environment variables:\n\n`echo "{{My path is $PATH}}"`\n\n- Print a message without the trailing newline:\n\n`echo -n "{{Hello World}}"`\n\n- Append a message to the file:\n\n`echo "{{Hello World}}" >> {{file.txt}}`\n\n- Enable interpretation of backslash escapes (special characters):\n\n`echo -e "{{Column 1\tColumn 2}}"`\n\n- Print the exit status of the last executed command (Note: In Windows Command Prompt and PowerShell the equivalent commands are `echo %errorlevel%` and `$lastexitcode` respectively):\n\n`echo $?`\n Task: search for the word echo all the bash files(files ending with .bash) in the current folder Bash Command:<START>find . -name "*.bash" |xargs grep "echo"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. echo(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training echo(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON ECHO(1) User Commands ECHO(1) NAME top echo - display a line of text SYNOPSIS top echo [SHORT-OPTION]... [STRING]... echo LONG-OPTION DESCRIPTION top Echo the STRING(s) to standard output. -n do not output the trailing newline -e enable interpretation of backslash escapes -E disable interpretation of backslash escapes (default) --help display this help and exit --version output version information and exit If -e is in effect, the following sequences are recognized: \\ backslash \a alert (BEL) \b backspace \c produce no further output \e escape \f form feed \n new line \r carriage return \t horizontal tab \v vertical tab \0NNN byte with octal value NNN (1 to 3 digits) \xHH byte with hexadecimal value HH (1 to 2 digits) NOTE: your shell may have its own version of echo, which usually supersedes the version described here. Please refer to your shell's documentation for details about the options it supports. NOTE: printf(1) is a preferred alternative, which does not have issues outputting option-like strings. AUTHOR top Written by Brian Fox and Chet Ramey. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top printf(1) Full documentation <https://www.gnu.org/software/coreutils/echo> or available locally via: info '(coreutils) echo invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 ECHO(1) Pages that refer to this page: ldapcompare(1), systemd-ask-password(1), systemd-run(1), cpuset(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word echo all the bash files(files ending with .bash) in the current folder Bash Command:<START>find . -name "*.bash" |xargs grep "echo"<END>
search for the word error in all the xml files in the current folder
find . -name "*.xml" -exec grep "ERROR" /dev/null '{}' \+
['find', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word error in all the xml files in the current folder Bash Command:<START>find . -name "*.xml" -exec grep "ERROR" /dev/null '{}' \+<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word error in all the xml files in the current folder Bash Command:<START>find . -name "*.xml" -exec grep "ERROR" /dev/null '{}' \+<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word error in all the xml files in the current folder Bash Command:<START>find . -name "*.xml" -exec grep "ERROR" /dev/null '{}' \+<END>
search for the word foo in all the js files in the current folder
find . -name "*.js" -exec grep -iH foo {} \;
['find', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word foo in all the js files in the current folder Bash Command:<START>find . -name "*.js" -exec grep -iH foo {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word foo in all the js files in the current folder Bash Command:<START>find . -name "*.js" -exec grep -iH foo {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word foo in all the js files in the current folder Bash Command:<START>find . -name "*.js" -exec grep -iH foo {} \;<END>
search for the word foo in all the js files in the current folder
grep -iH foo `find . -name "*.js"`
['find', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word foo in all the js files in the current folder Bash Command:<START>grep -iH foo `find . -name "*.js"`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word foo in all the js files in the current folder Bash Command:<START>grep -iH foo `find . -name "*.js"`<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word foo in all the js files in the current folder Bash Command:<START>grep -iH foo `find . -name "*.js"`<END>
search for the word hello in all the text files in the temp folder and delete them
find /tmp -type f -name ‘*.txt*’ | sed -e ‘s/.*/\”&\”/’ |xargs -n 1 grep -l hello|sed -e ‘s/.*/\”&\”/’|xargs -n 1 rm -f
['find', 'xargs', 'sed', 'grep', 'rm']
Output a Bash command to accomplish the following task. Task: search for the word hello in all the text files in the temp folder and delete them Bash Command:<START>find /tmp -type f -name ‘*.txt*’ | sed -e ‘s/.*/\”&\”/’ |xargs -n 1 grep -l hello|sed -e ‘s/.*/\”&\”/’|xargs -n 1 rm -f<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # sed\n\n> Edit text in a scriptable manner.\n> See also: `awk`, `ed`.\n> More information: <https://www.gnu.org/software/sed/manual/sed.html>.\n\n- Replace all `apple` (basic regex) occurrences with `mango` (basic regex) in all input lines and print the result to `stdout`:\n\n`{{command}} | sed 's/apple/mango/g'`\n\n- Replace all `apple` (extended regex) occurrences with `APPLE` (extended regex) in all input lines and print the result to `stdout`:\n\n`{{command}} | sed -E 's/(apple)/\U\1/g'`\n\n- Replace all `apple` (basic regex) occurrences with `mango` (basic regex) in a specific file and overwrite the original file in place:\n\n`sed -i 's/apple/mango/g' {{path/to/file}}`\n\n- Execute a specific script [f]ile and print the result to `stdout`:\n\n`{{command}} | sed -f {{path/to/script.sed}}`\n\n- Print just the first line to `stdout`:\n\n`{{command}} | sed -n '1p'`\n\n- [d]elete the first line of a file:\n\n`sed -i 1d {{path/to/file}}`\n\n- [i]nsert a new line at the first line of a file:\n\n`sed -i '1i\your new line text\' {{path/to/file}}`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n # rm\n\n> Remove files or directories.\n> See also: `rmdir`.\n> More information: <https://www.gnu.org/software/coreutils/rm>.\n\n- Remove specific files:\n\n`rm {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files ignoring nonexistent ones:\n\n`rm --force {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files interactively prompting before each removal:\n\n`rm --interactive {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files printing info about each removal:\n\n`rm --verbose {{path/to/file1 path/to/file2 ...}}`\n\n- Remove specific files and directories recursively:\n\n`rm --recursive {{path/to/file_or_directory1 path/to/file_or_directory2 ...}}`\n Task: search for the word hello in all the text files in the temp folder and delete them Bash Command:<START>find /tmp -type f -name ‘*.txt*’ | sed -e ‘s/.*/\”&\”/’ |xargs -n 1 grep -l hello|sed -e ‘s/.*/\”&\”/’|xargs -n 1 rm -f<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. sed(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training sed(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | COMMAND SYNOPSIS | REGULAR EXPRESSIONS | BUGS | AUTHOR | COPYRIGHT | SEE ALSO | COLOPHON SED(1) User Commands SED(1) NAME top sed - stream editor for filtering and transforming text SYNOPSIS top sed [-V] [--version] [--help] [-n] [--quiet] [--silent] [-l N] [--line-length=N] [-u] [--unbuffered] [-E] [-r] [--regexp-extended] [-e script] [--expression=script] [-f script-file] [--file=script-file] [script-if-no-other-script] [file...] DESCRIPTION top Sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed's ability to filter text in a pipeline which particularly distinguishes it from other types of editors. -n, --quiet, --silent suppress automatic printing of pattern space --debug annotate program execution -e script, --expression=script add the script to the commands to be executed -f script-file, --file=script-file add the contents of script-file to the commands to be executed --follow-symlinks follow symlinks when processing in place -i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if SUFFIX supplied) -l N, --line-length=N specify the desired line-wrap length for the `l' command --posix disable all GNU extensions. -E, -r, --regexp-extended use extended regular expressions in the script (for portability use POSIX -E). -s, --separate consider files as separate rather than as a single, continuous long stream. --sandbox operate in sandbox mode (disable e/r/w commands). -u, --unbuffered load minimal amounts of data from the input files and flush the output buffers more often -z, --null-data separate lines by NUL characters --help display this help and exit --version output version information and exit If no -e, --expression, -f, or --file option is given, then the first non-option argument is taken as the sed script to interpret. All remaining arguments are names of input files; if no input files are specified, then the standard input is read. GNU sed home page: <https://www.gnu.org/software/sed/>. General help using GNU software: <https://www.gnu.org/gethelp/>. E-mail bug reports to: <bug-sed@gnu.org>. COMMAND SYNOPSIS top This is just a brief synopsis of sed commands to serve as a reminder to those who already know sed; other documentation (such as the texinfo document) must be consulted for fuller descriptions. Zero-address ``commands'' : label Label for b and t commands. #comment The comment extends until the next newline (or the end of a -e script fragment). } The closing bracket of a { } block. Zero- or One- address commands = Print the current line number. a \ text Append text, which has each embedded newline preceded by a backslash. i \ text Insert text, which has each embedded newline preceded by a backslash. q [exit-code] Immediately quit the sed script without processing any more input, except that if auto-print is not disabled the current pattern space will be printed. The exit code argument is a GNU extension. Q [exit-code] Immediately quit the sed script without processing any more input. This is a GNU extension. r filename Append text read from filename. R filename Append a line read from filename. Each invocation of the command reads a line from the file. This is a GNU extension. Commands which accept address ranges { Begin a block of commands (end with a }). b label Branch to label; if label is omitted, branch to end of script. c \ text Replace the selected lines with text, which has each embedded newline preceded by a backslash. d Delete pattern space. Start next cycle. D If pattern space contains no newline, start a normal new cycle as if the d command was issued. Otherwise, delete text in the pattern space up to the first newline, and restart cycle with the resultant pattern space, without reading a new line of input. h H Copy/append pattern space to hold space. g G Copy/append hold space to pattern space. l List out the current line in a ``visually unambiguous'' form. l width List out the current line in a ``visually unambiguous'' form, breaking it at width characters. This is a GNU extension. n N Read/append the next line of input into the pattern space. p Print the current pattern space. P Print up to the first embedded newline of the current pattern space. s/regexp/replacement/ Attempt to match regexp against the pattern space. If successful, replace that portion matched with replacement. The replacement may contain the special character & to refer to that portion of the pattern space which matched, and the special escapes \1 through \9 to refer to the corresponding matching sub-expressions in the regexp. t label If a s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script. T label If no s/// has done a successful substitution since the last input line was read and since the last t or T command, then branch to label; if label is omitted, branch to end of script. This is a GNU extension. w filename Write the current pattern space to filename. W filename Write the first line of the current pattern space to filename. This is a GNU extension. x Exchange the contents of the hold and pattern spaces. y/source/dest/ Transliterate the characters in the pattern space which appear in source to the corresponding character in dest. Addresses Sed commands can be given with no addresses, in which case the command will be executed for all input lines; with one address, in which case the command will only be executed for input lines which match that address; or with two addresses, in which case the command will be executed for all input lines which match the inclusive range of lines starting from the first address and continuing to the second address. Three things to note about address ranges: the syntax is addr1,addr2 (i.e., the addresses are separated by a comma); the line which addr1 matched will always be accepted, even if addr2 selects an earlier line; and if addr2 is a regexp, it will not be tested against the line that addr1 matched. After the address (or address-range), and before the command, a ! may be inserted, which specifies that the command shall only be executed if the address (or address-range) does not match. The following address types are supported: number Match only the specified line number (which increments cumulatively across files, unless the -s option is specified on the command line). first~step Match every step'th line starting with line first. For example, ``sed -n 1~2p'' will print all the odd-numbered lines in the input stream, and the address 2~5 will match every fifth line, starting with the second. first can be zero; in this case, sed operates as if it were equal to step. (This is an extension.) $ Match the last line. /regexp/ Match lines matching the regular expression regexp. Matching is performed on the current pattern space, which can be modified with commands such as ``s///''. \cregexpc Match lines matching the regular expression regexp. The c may be any character. GNU sed also supports some special 2-address forms: 0,addr2 Start out in "matched first address" state, until addr2 is found. This is similar to 1,addr2, except that if addr2 matches the very first line of input the 0,addr2 form will be at the end of its range, whereas the 1,addr2 form will still be at the beginning of its range. This works only when addr2 is a regular expression. addr1,+N Will match addr1 and the N lines following addr1. addr1,~N Will match addr1 and the lines following addr1 until the next line whose input line number is a multiple of N. REGULAR EXPRESSIONS top POSIX.2 BREs should be supported, but they aren't completely because of performance problems. The \n sequence in a regular expression matches the newline character, and similarly for \a, \t, and other sequences. The -E option switches to using extended regular expressions instead; it has been supported for years by GNU sed, and is now included in POSIX. BUGS top E-mail bug reports to bug-sed@gnu.org. Also, please include the output of ``sed --version'' in the body of your report if at all possible. AUTHOR top Written by Jay Fenlason, Tom Lord, Ken Pizzini, Paolo Bonzini, Jim Meyering, and Assaf Gordon. This sed program was built with SELinux support. SELinux is enabled on this system. GNU sed home page: <https://www.gnu.org/software/sed/>. General help using GNU software: <https://www.gnu.org/gethelp/>. E-mail bug reports to: <bug-sed@gnu.org>. COPYRIGHT top Copyright 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. SEE ALSO top awk(1), ed(1), grep(1), tr(1), perlre(1), sed.info, any of various books on sed, the sed FAQ (http://sed.sf.net/grabbag/tutorials/sedfaq.txt), http://sed.sf.net/grabbag/. The full documentation for sed is maintained as a Texinfo manual. If the info and sed programs are properly installed at your site, the command info sed should give you access to the complete manual. COLOPHON top This page is part of the sed (stream-oriented editor) project. Information about the project can be found at http://www.gnu.org/software/sed/. If you have a bug report for this manual page, send it to bug-sed@gnu.org. This page was obtained from the tarball sed-4.9.tar.gz fetched from https://www.gnu.org/software/sed/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU sed 4.9 November 2022 SED(1) Pages that refer to this page: gawk(1), grep(1), iostat2pcp(1), pmdaopenmetrics(1), pmlogrewrite(1), sheet2pcp(1), cpuset(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. rm(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training rm(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON RM(1) User Commands RM(1) NAME top rm - remove files or directories SYNOPSIS top rm [OPTION]... [FILE]... DESCRIPTION top This manual page documents the GNU version of rm. rm removes each specified file. By default, it does not remove directories. If the -I or --interactive=once option is given, and there are more than three files or the -r, -R, or --recursive are given, then rm prompts the user for whether to proceed with the entire operation. If the response is not affirmative, the entire command is aborted. Otherwise, if a file is unwritable, standard input is a terminal, and the -f or --force option is not given, or the -i or --interactive=always option is given, rm prompts the user for whether to remove the file. If the response is not affirmative, the file is skipped. OPTIONS top Remove (unlink) the FILE(s). -f, --force ignore nonexistent files and arguments, never prompt -i prompt before every removal -I prompt once before removing more than three files, or when removing recursively; less intrusive than -i, while still giving protection against most mistakes --interactive[=WHEN] prompt according to WHEN: never, once (-I), or always (-i); without WHEN, prompt always --one-file-system when removing a hierarchy recursively, skip any directory that is on a file system different from that of the corresponding command line argument --no-preserve-root do not treat '/' specially --preserve-root[=all] do not remove '/' (default); with 'all', reject any command line argument on a separate device from its parent -r, -R, --recursive remove directories and their contents recursively -d, --dir remove empty directories -v, --verbose explain what is being done --help display this help and exit --version output version information and exit By default, rm does not remove directories. Use the --recursive (-r or -R) option to remove each listed directory, too, along with all of its contents. To remove a file whose name starts with a '-', for example '-foo', use one of these commands: rm -- -foo rm ./-foo Note that if you use rm to remove a file, it might be possible to recover some of its contents, given sufficient expertise and/or time. For greater assurance that the contents are truly unrecoverable, consider using shred(1). AUTHOR top Written by Paul Rubin, David MacKenzie, Richard M. Stallman, and Jim Meyering. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top unlink(1), unlink(2), chattr(1), shred(1) Full documentation <https://www.gnu.org/software/coreutils/rm> or available locally via: info '(coreutils) rm invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 RM(1) Pages that refer to this page: rmdir(2), unlink(2), remove(3), mq_overview(7), symlink(7), debugfs(8), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word hello in all the text files in the temp folder and delete them Bash Command:<START>find /tmp -type f -name ‘*.txt*’ | sed -e ‘s/.*/\”&\”/’ |xargs -n 1 grep -l hello|sed -e ‘s/.*/\”&\”/’|xargs -n 1 rm -f<END>
search for the word text in all the python files in the current folder
find . -iname '*py' -exec grep "text" {} \;
['find', 'grep']
Output a Bash command to accomplish the following task. Task: search for the word text in all the python files in the current folder Bash Command:<START>find . -iname '*py' -exec grep "text" {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for the word text in all the python files in the current folder Bash Command:<START>find . -iname '*py' -exec grep "text" {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for the word text in all the python files in the current folder Bash Command:<START>find . -iname '*py' -exec grep "text" {} \;<END>
search for version in system.info files.
find /home/*/public_html/ -type f -iwholename "*/modules/system/system.info" -exec grep -H "version = \"" {} \;
['find', 'grep']
Output a Bash command to accomplish the following task. Task: search for version in system.info files. Bash Command:<START>find /home/*/public_html/ -type f -iwholename "*/modules/system/system.info" -exec grep -H "version = \"" {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for version in system.info files. Bash Command:<START>find /home/*/public_html/ -type f -iwholename "*/modules/system/system.info" -exec grep -H "version = \"" {} \;<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for version in system.info files. Bash Command:<START>find /home/*/public_html/ -type f -iwholename "*/modules/system/system.info" -exec grep -H "version = \"" {} \;<END>
search for word linux in all the regular/normal files in the folder mail.
find ~/mail -type f | xargs grep "Linux"
['find', 'xargs', 'grep']
Output a Bash command to accomplish the following task. Task: search for word linux in all the regular/normal files in the folder mail. Bash Command:<START>find ~/mail -type f | xargs grep "Linux"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # xargs\n\n> Execute a command with piped arguments coming from another command, a file, etc.\n> The input is treated as a single block of text and split into separate pieces on spaces, tabs, newlines and end-of-file.\n> More information: <https://pubs.opengroup.org/onlinepubs/9699919799/utilities/xargs.html>.\n\n- Run a command using the input data as arguments:\n\n`{{arguments_source}} | xargs {{command}}`\n\n- Run multiple chained commands on the input data:\n\n`{{arguments_source}} | xargs sh -c "{{command1}} && {{command2}} | {{command3}}"`\n\n- Delete all files with a `.backup` extension (`-print0` uses a null character to split file names, and `-0` uses it as delimiter):\n\n`find . -name {{'*.backup'}} -print0 | xargs -0 rm -v`\n\n- Execute the command once for each input line, replacing any occurrences of the placeholder (here marked as `_`) with the input line:\n\n`{{arguments_source}} | xargs -I _ {{command}} _ {{optional_extra_arguments}}`\n\n- Parallel runs of up to `max-procs` processes at a time; the default is 1. If `max-procs` is 0, xargs will run as many processes as possible at a time:\n\n`{{arguments_source}} | xargs -P {{max-procs}} {{command}}`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search for word linux in all the regular/normal files in the folder mail. Bash Command:<START>find ~/mail -type f | xargs grep "Linux"<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. xargs(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training xargs(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXAMPLES | EXIT STATUS | STANDARDS CONFORMANCE | HISTORY | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON XARGS(1) General Commands Manual XARGS(1) NAME top xargs - build and execute command lines from standard input SYNOPSIS top xargs [options] [command [initial-arguments]] DESCRIPTION top This manual page documents the GNU version of xargs. xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input. Blank lines on the standard input are ignored. The command line for command is built up until it reaches a system-defined limit (unless the -n and -L options are used). The specified command will be invoked as many times as necessary to use up the list of input items. In general, there will be many fewer invocations of command than there were items in the input. This will normally have significant performance benefits. Some commands can usefully be executed in parallel too; see the -P option. Because Unix filenames can contain blanks and newlines, this default behaviour is often problematic; filenames containing blanks and/or newlines are incorrectly processed by xargs. In these situations it is better to use the -0 option, which prevents such problems. When using this option you will need to ensure that the program which produces the input for xargs also uses a null character as a separator. If that program is GNU find for example, the -print0 option does this for you. If any invocation of the command exits with a status of 255, xargs will stop immediately without reading any further input. An error message is issued on stderr when this happens. OPTIONS top -0, --null Input items are terminated by a null character instead of by whitespace, and the quotes and backslash are not special (every character is taken literally). Disables the end-of-file string, which is treated like any other argument. Useful when input items might contain white space, quote marks, or backslashes. The GNU find -print0 option produces input suitable for this mode. -a file, --arg-file=file Read items from file instead of standard input. If you use this option, stdin remains unchanged when commands are run. Otherwise, stdin is redirected from /dev/null. --delimiter=delim, -d delim Input items are terminated by the specified character. The specified delimiter may be a single character, a C- style character escape such as \n, or an octal or hexadecimal escape code. Octal and hexadecimal escape codes are understood as for the printf command. Multibyte characters are not supported. When processing the input, quotes and backslash are not special; every character in the input is taken literally. The -d option disables any end-of-file string, which is treated like any other argument. You can use this option when the input consists of simply newline-separated items, although it is almost always better to design your program to use --null where this is possible. -E eof-str Set the end-of-file string to eof-str. If the end-of-file string occurs as a line of input, the rest of the input is ignored. If neither -E nor -e is used, no end-of-file string is used. -e[eof-str], --eof[=eof-str] This option is a synonym for the -E option. Use -E instead, because it is POSIX compliant while this option is not. If eof-str is omitted, there is no end-of-file string. If neither -E nor -e is used, no end-of-file string is used. -I replace-str Replace occurrences of replace-str in the initial- arguments with names read from standard input. Also, unquoted blanks do not terminate input items; instead the separator is the newline character. Implies -x and -L 1. -i[replace-str], --replace[=replace-str] This option is a synonym for -Ireplace-str if replace-str is specified. If the replace-str argument is missing, the effect is the same as -I{}. The -i option is deprecated; use -I instead. -L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. -l[max-lines], --max-lines[=max-lines] Synonym for the -L option. Unlike -L, the max-lines argument is optional. If max-lines is not specified, it defaults to one. The -l option is deprecated since the POSIX standard specifies -L instead. -n max-args, --max-args=max-args Use at most max-args arguments per command line. Fewer than max-args arguments will be used if the size (see the -s option) is exceeded, unless the -x option is given, in which case xargs will exit. -P max-procs, --max-procs=max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option or the -L option with -P; otherwise chances are that only one exec will be done. While xargs is running, you can send its process a SIGUSR1 signal to increase the number of commands to run simultaneously, or a SIGUSR2 to decrease the number. You cannot increase it above an implementation-defined limit (which is shown with --show-limits). You cannot decrease it below 1. xargs never terminates its commands; when asked to decrease, it merely waits for more than one existing command to terminate before starting another. Please note that it is up to the called processes to properly manage parallel access to shared resources. For example, if more than one of them tries to print to stdout, the output will be produced in an indeterminate order (and very likely mixed up) unless the processes collaborate in some way to prevent this. Using some kind of locking scheme is one way to prevent such problems. In general, using a locking scheme will help ensure correct output but reduce performance. If you don't want to tolerate the performance difference, simply arrange for each process to produce a separate output file (or otherwise use separate resources). -o, --open-tty Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application. -p, --interactive Prompt the user about whether to run each command line and read a line from the terminal. Only run the command line if the response starts with `y' or `Y'. Implies -t. --process-slot-var=name Set the environment variable name to a unique value in each running child process. Values are reused once child processes exit. This can be used in a rudimentary load distribution scheme, for example. -r, --no-run-if-empty If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension. -s max-chars, --max-chars=max-chars Use at most max-chars characters per command line, including the command and initial-arguments and the terminating nulls at the ends of the argument strings. The largest allowed value is system-dependent, and is calculated as the argument length limit for exec, less the size of your environment, less 2048 bytes of headroom. If this value is more than 128 KiB, 128 KiB is used as the default value; otherwise, the default value is the maximum. 1 KiB is 1024 bytes. xargs automatically adapts to tighter constraints. --show-limits Display the limits on the command-line length which are imposed by the operating system, xargs' choice of buffer size and the -s option. Pipe the input from /dev/null (and perhaps specify --no-run-if-empty) if you don't want xargs to do anything. -t, --verbose Print the command line on the standard error output before executing it. -x, --exit Exit if the size (see the -s option) is exceeded. -- Delimit the option list. Later arguments, if any, are treated as operands even if they begin with -. For example, xargs -- --help runs the command --help (found in PATH) instead of printing the usage text, and xargs -- --mycommand runs the command --mycommand instead of rejecting this as unrecognized option. --help Print a summary of the options to xargs and exit. --version Print the version number of xargs and exit. The options --max-lines (-L, -l), --replace (-I, -i) and --max- args (-n) are mutually exclusive. If some of them are specified at the same time, then xargs will generally use the option specified last on the command line, i.e., it will reset the value of the offending option (given before) to its default value. Additionally, xargs will issue a warning diagnostic on stderr. The exception to this rule is that the special max-args value 1 ('-n1') is ignored after the --replace option and its aliases -I and -i, because it would not actually conflict. EXAMPLES top find /tmp -name core -type f -print | xargs /bin/rm -f Find files named core in or below the directory /tmp and delete them. Note that this will work incorrectly if there are any filenames containing newlines or spaces. find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f 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 spaces or newlines are correctly handled. find /tmp -depth -name core -type f -delete Find files named core in or below the directory /tmp and delete them, but more efficiently than in the previous example (because we avoid the need to use fork(2) and exec(2) to launch rm and we don't need the extra xargs process). cut -d: -f1 < /etc/passwd | sort | xargs echo Generates a compact listing of all the users on the system. EXIT STATUS top xargs exits with the following status: 0 if it succeeds 123 if any invocation of the command exited with status 1125 124 if the command exited with status 255 125 if the command is killed by a signal 126 if the command cannot be run 127 if the command is not found 1 if some other error occurred. Exit codes greater than 128 are used by the shell to indicate that a program died due to a fatal signal. STANDARDS CONFORMANCE top As of GNU xargs version 4.2.9, the default behaviour of xargs is not to have a logical end-of-file marker. POSIX (IEEE Std 1003.1, 2004 Edition) allows this. The -l and -i options appear in the 1997 version of the POSIX standard, but do not appear in the 2004 version of the standard. Therefore you should use -L and -I instead, respectively. The -o option is an extension to the POSIX standard for better compatibility with BSD. The POSIX standard allows implementations to have a limit on the size of arguments to the exec functions. This limit could be as low as 4096 bytes including the size of the environment. For scripts to be portable, they must not rely on a larger value. However, I know of no implementation whose actual limit is that small. The --show-limits option can be used to discover the actual limits in force on the current system. HISTORY top The xargs program was invented by Herb Gellis at Bell Labs. See the Texinfo manual for findutils, Finding Files, for more information. BUGS top It is not possible for xargs to be used securely, since there will always be a time gap between the production of the list of input files and their use in the commands that xargs issues. If other users have access to the system, they can manipulate the filesystem during this time window to force the action of the commands xargs runs to apply to files that you didn't intend. For a more detailed discussion of this and related problems, please refer to the ``Security Considerations'' chapter in the findutils Texinfo documentation. The -execdir option of find can often be used as a more secure alternative. When you use the -I option, each line read from the input is buffered internally. This means that there is an upper limit on the length of input line that xargs will accept when used with the -I option. To work around this limitation, you can use the -s option to increase the amount of buffer space that xargs uses, and you can also use an extra invocation of xargs to ensure that very long lines do not occur. For example: somecommand | xargs -s 50000 echo | xargs -I '{}' -s 100000 rm '{}' Here, the first invocation of xargs has no input line length limit because it doesn't use the -i option. The second invocation of xargs does have such a limit, but we have ensured that it never encounters a line which is longer than it can handle. This is not an ideal solution. Instead, the -i option should not impose a line length limit, which is why this discussion appears in the BUGS section. The problem doesn't occur with the output of find(1) because it emits just one filename per line. REPORTING BUGS top 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 top Copyright 19902023 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 top find(1), kill(1), locate(1), updatedb(1), fork(2), execvp(3), locatedb(5), signal(7) Full documentation <https://www.gnu.org/software/findutils/xargs> or available locally via: info xargs COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org XARGS(1) Pages that refer to this page: dpkg-name(1), find(1), grep(1), locate(1), updatedb(1), lsof(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search for word linux in all the regular/normal files in the folder mail. Bash Command:<START>find ~/mail -type f | xargs grep "Linux"<END>
search in all the regular/normal files of the current folder for the word "word" and display the matched file name
find . -type f -exec grep -l "word" {} +
['find', 'grep']
Output a Bash command to accomplish the following task. Task: search in all the regular/normal files of the current folder for the word "word" and display the matched file name Bash Command:<START>find . -type f -exec grep -l "word" {} +<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # grep\n\n> Find patterns in files using regular expressions.\n> More information: <https://www.gnu.org/software/grep/manual/grep.html>.\n\n- Search for a pattern within a file:\n\n`grep "{{search_pattern}}" {{path/to/file}}`\n\n- Search for an exact string (disables regular expressions):\n\n`grep --fixed-strings "{{exact_string}}" {{path/to/file}}`\n\n- Search for a pattern in all files recursively in a directory, showing line numbers of matches, ignoring binary files:\n\n`grep --recursive --line-number --binary-files={{without-match}} "{{search_pattern}}" {{path/to/directory}}`\n\n- Use extended regular expressions (supports `?`, `+`, `{}`, `()` and `|`), in case-insensitive mode:\n\n`grep --extended-regexp --ignore-case "{{search_pattern}}" {{path/to/file}}`\n\n- Print 3 lines of context around, before, or after each match:\n\n`grep --{{context|before-context|after-context}}={{3}} "{{search_pattern}}" {{path/to/file}}`\n\n- Print file name and line number for each match with color output:\n\n`grep --with-filename --line-number --color=always "{{search_pattern}}" {{path/to/file}}`\n\n- Search for lines matching a pattern, printing only the matched text:\n\n`grep --only-matching "{{search_pattern}}" {{path/to/file}}`\n\n- Search `stdin` for lines that do not match a pattern:\n\n`cat {{path/to/file}} | grep --invert-match "{{search_pattern}}"`\n Task: search in all the regular/normal files of the current folder for the word "word" and display the matched file name Bash Command:<START>find . -type f -exec grep -l "word" {} +<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. grep(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training grep(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | REGULAR EXPRESSIONS | EXIT STATUS | ENVIRONMENT | NOTES | COPYRIGHT | BUGS | EXAMPLE | SEE ALSO | COLOPHON GREP(1) User Commands GREP(1) NAME top grep - print lines that match patterns SYNOPSIS top grep [OPTION...] PATTERNS [FILE...] grep [OPTION...] -e PATTERNS ... [FILE...] grep [OPTION...] -f PATTERN_FILE ... [FILE...] DESCRIPTION top grep searches for PATTERNS in each FILE. PATTERNS is one or more patterns separated by newline characters, and grep prints each line that matches a pattern. Typically PATTERNS should be quoted when grep is used in a shell command. A FILE of - stands for standard input. If no FILE is given, recursive searches examine the working directory, and nonrecursive searches read standard input. OPTIONS top Generic Program Information --help Output a usage message and exit. -V, --version Output the version number of grep and exit. Pattern Syntax -E, --extended-regexp Interpret PATTERNS as extended regular expressions (EREs, see below). -F, --fixed-strings Interpret PATTERNS as fixed strings, not regular expressions. -G, --basic-regexp Interpret PATTERNS as basic regular expressions (BREs, see below). This is the default. -P, --perl-regexp Interpret PATTERNS as Perl-compatible regular expressions (PCREs). This option is experimental when combined with the -z (--null-data) option, and grep -P may warn of unimplemented features. Matching Control -e PATTERNS, --regexp=PATTERNS Use PATTERNS as the patterns. If this option is used multiple times or is combined with the -f (--file) option, search for all patterns given. This option can be used to protect a pattern beginning with -. -f FILE, --file=FILE Obtain patterns from FILE, one per line. If this option is used multiple times or is combined with the -e (--regexp) option, search for all patterns given. The empty file contains zero patterns, and therefore matches nothing. If FILE is - , read patterns from standard input. -i, --ignore-case Ignore case distinctions in patterns and input data, so that characters that differ only in case match each other. --no-ignore-case Do not ignore case distinctions in patterns and input data. This is the default. This option is useful for passing to shell scripts that already use -i, to cancel its effects because the two options override each other. -v, --invert-match Invert the sense of matching, to select non-matching lines. -w, --word-regexp Select only those lines containing matches that form whole words. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. Similarly, it must be either at the end of the line or followed by a non-word constituent character. Word-constituent characters are letters, digits, and the underscore. This option has no effect if -x is also specified. -x, --line-regexp Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $. General Output Control -c, --count Suppress normal output; instead print a count of matching lines for each input file. With the -v, --invert-match option (see above), count non-matching lines. --color[=WHEN], --colour[=WHEN] Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. The colors are defined by the environment variable GREP_COLORS. WHEN is never, always, or auto. -L, --files-without-match Suppress normal output; instead print the name of each input file from which no output would normally have been printed. -l, --files-with-matches Suppress normal output; instead print the name of each input file from which output would normally have been printed. Scanning each input file stops upon first match. -m NUM, --max-count=NUM Stop reading a file after NUM matching lines. If NUM is zero, grep stops right away without reading input. A NUM of -1 is treated as infinity and grep does not stop; this is the default. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines. -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line. -q, --quiet, --silent Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option. -s, --no-messages Suppress error messages about nonexistent or unreadable files. Output Line Prefix Control -b, --byte-offset Print the 0-based byte offset within the input file before each line of output. If -o (--only-matching) is specified, print the offset of the matching part itself. -H, --with-filename Print the file name for each match. This is the default when there is more than one file to search. This is a GNU extension. -h, --no-filename Suppress the prefixing of file names on output. This is the default when there is only one file (or only standard input) to search. --label=LABEL Display input actually coming from standard input as input coming from file LABEL. This can be useful for commands that transform a file's contents before searching, e.g., gzip -cd foo.gz | grep --label=foo -H 'some pattern'. See also the -H option. -n, --line-number Prefix each line of output with the 1-based line number within its input file. -T, --initial-tab Make sure that the first character of actual line content lies on a tab stop, so that the alignment of tabs looks normal. This is useful with options that prefix their output to the actual content: -H,-n, and -b. In order to improve the probability that lines from a single file will all start at the same column, this also causes the line number and byte offset (if present) to be printed in a minimum size field width. -Z, --null Output a zero byte (the ASCII NUL character) instead of the character that normally follows a file name. For example, grep -lZ outputs a zero byte after each file name instead of the usual newline. This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines. This option can be used with commands like find -print0, perl -0, sort -z, and xargs -0 to process arbitrary file names, even those that contain newline characters. Context Line Control -A NUM, --after-context=NUM Print NUM lines of trailing context after matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -B NUM, --before-context=NUM Print NUM lines of leading context before matching lines. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. -C NUM, -NUM, --context=NUM Print NUM lines of output context. Places a line containing a group separator (--) between contiguous groups of matches. With the -o or --only-matching option, this has no effect and a warning is given. --group-separator=SEP When -A, -B, or -C are in use, print SEP instead of -- between groups of lines. --no-group-separator When -A, -B, or -C are in use, do not print a separator between groups of lines. File and Directory Selection -a, --text Process a binary file as if it were text; this is equivalent to the --binary-files=text option. --binary-files=TYPE If a file's data or metadata indicate that the file contains binary data, assume that the file is of type TYPE. Non-text bytes indicate binary data; these are either output bytes that are improperly encoded for the current locale, or null input bytes when the -z option is not given. By default, TYPE is binary, and grep suppresses output after null input binary data is discovered, and suppresses output lines that contain improperly encoded data. When some output is suppressed, grep follows any output with a message to standard error saying that a binary file matches. If TYPE is without-match, when grep discovers null input binary data it assumes that the rest of the file does not match; this is equivalent to the -I option. If TYPE is text, grep processes a binary file as if it were text; this is equivalent to the -a option. When type is binary, grep may treat non-text bytes as line terminators even without the -z option. This means choosing binary versus text can affect whether a pattern matches a file. For example, when type is binary the pattern q$ might match q immediately followed by a null byte, even though this is not matched when type is text. Conversely, when type is binary the pattern . (period) might not match a null byte. Warning: The -a option might output binary garbage, which can have nasty side effects if the output is a terminal and if the terminal driver interprets some of it as commands. On the other hand, when reading files whose text encodings are unknown, it can be helpful to use -a or to set LC_ALL='C' in the environment, in order to find more matches even if the matches are unsafe for direct display. -D ACTION, --devices=ACTION If an input file is a device, FIFO or socket, use ACTION to process it. By default, ACTION is read, which means that devices are read just as if they were ordinary files. If ACTION is skip, devices are silently skipped. -d ACTION, --directories=ACTION If an input file is a directory, use ACTION to process it. By default, ACTION is read, i.e., read directories just as if they were ordinary files. If ACTION is skip, silently skip directories. If ACTION is recurse, read all files under each directory, recursively, following symbolic links only if they are on the command line. This is equivalent to the -r option. --exclude=GLOB Skip any command-line file with a name suffix that matches the pattern GLOB, using wildcard matching; a name suffix is either the whole name, or a trailing part that starts with a non-slash character immediately after a slash (/) in the name. When searching recursively, skip any subfile whose base name matches GLOB; the base name is the part after the last slash. A pattern can use *, ?, and [...] as wildcards, and \ to quote a wildcard or backslash character literally. --exclude-from=FILE Skip files whose base name matches any of the file-name globs read from FILE (using wildcard matching as described under --exclude). --exclude-dir=GLOB Skip any command-line directory with a name suffix that matches the pattern GLOB. When searching recursively, skip any subdirectory whose base name matches GLOB. Ignore any redundant trailing slashes in GLOB. -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option. --include=GLOB Search only files whose base name matches GLOB (using wildcard matching as described under --exclude). If contradictory --include and --exclude options are given, the last matching one wins. If no --include or --exclude options match, a file is included unless the first such option is --include. -r, --recursive Read all files under each directory, recursively, following symbolic links only if they are on the command line. Note that if no file operand is given, grep searches the working directory. This is equivalent to the -d recurse option. -R, --dereference-recursive Read all files under each directory, recursively. Follow all symbolic links, unlike -r. Other Options --line-buffered Use line buffering on output. This can cause a performance penalty. -U, --binary Treat the file(s) as binary. By default, under MS-DOS and MS-Windows, grep guesses whether a file is text or binary as described for the --binary-files option. If grep decides the file is a text file, it strips the CR characters from the original file contents (to make regular expressions with ^ and $ work correctly). Specifying -U overrules this guesswork, causing all files to be read and passed to the matching mechanism verbatim; if the file is a text file with CR/LF pairs at the end of each line, this will cause some regular expressions to fail. This option has no effect on platforms other than MS-DOS and MS-Windows. -z, --null-data Treat input and output data as sequences of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like sort -z to process arbitrary file names. REGULAR EXPRESSIONS top A regular expression is a pattern that describes a set of strings. Regular expressions are constructed analogously to arithmetic expressions, by using various operators to combine smaller expressions. grep understands three different versions of regular expression syntax: basic (BRE), extended (ERE) and perl (PCRE). In GNU grep, basic and extended regular expressions are merely different notations for the same pattern-matching functionality. In other implementations, basic regular expressions are ordinarily less powerful than extended, though occasionally it is the other way around. The following description applies to extended regular expressions; differences for basic regular expressions are summarized afterwards. Perl-compatible regular expressions have different functionality, and are documented in pcre2syntax(3) and pcre2pattern(3), but work only if PCRE support is enabled. The fundamental building blocks are the regular expressions that match a single character. Most characters, including all letters and digits, are regular expressions that match themselves. Any meta-character with special meaning may be quoted by preceding it with a backslash. The period . matches any single character. It is unspecified whether it matches an encoding error. Character Classes and Bracket Expressions A bracket expression is a list of characters enclosed by [ and ]. It matches any single character in that list. If the first character of the list is the caret ^ then it matches any character not in the list; it is unspecified whether it matches an encoding error. For example, the regular expression [0123456789] matches any single digit. Within a bracket expression, a range expression consists of two characters separated by a hyphen. It matches any single character that sorts between the two characters, inclusive, using the locale's collating sequence and character set. For example, in the default C locale, [a-d] is equivalent to [abcd]. Many locales sort characters in dictionary order, and in these locales [a-d] is typically not equivalent to [abcd]; it might be equivalent to [aBbCcDd], for example. To obtain the traditional interpretation of bracket expressions, you can use the C locale by setting the LC_ALL environment variable to the value C. Finally, certain named classes of characters are predefined within bracket expressions, as follows. Their names are self explanatory, and they are [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], and [:xdigit:]. For example, [[:alnum:]] means the character class of numbers and letters in the current locale. In the C locale and ASCII character set encoding, this is the same as [0-9A-Za-z]. (Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.) Most meta-characters lose their special meaning inside bracket expressions. To include a literal ] place it first in the list. Similarly, to include a literal ^ place it anywhere but first. Finally, to include a literal - place it last. Anchoring The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line. The Backslash Character and Special Expressions The symbols \< and \> respectively match the empty string at the beginning and end of a word. The symbol \b matches the empty string at the edge of a word, and \B matches the empty string provided it's not at the edge of a word. The symbol \w is a synonym for [_[:alnum:]] and \W is a synonym for [^_[:alnum:]]. Repetition A regular expression may be followed by one of several repetition operators: ? The preceding item is optional and matched at most once. * The preceding item will be matched zero or more times. + The preceding item will be matched one or more times. {n} The preceding item is matched exactly n times. {n,} The preceding item is matched n or more times. {,m} The preceding item is matched at most m times. This is a GNU extension. {n,m} The preceding item is matched at least n times, but not more than m times. Concatenation Two regular expressions may be concatenated; the resulting regular expression matches any string formed by concatenating two substrings that respectively match the concatenated expressions. Alternation Two regular expressions may be joined by the infix operator |; the resulting regular expression matches any string matching either alternate expression. Precedence Repetition takes precedence over concatenation, which in turn takes precedence over alternation. A whole expression may be enclosed in parentheses to override these precedence rules and form a subexpression. Back-references and Subexpressions The back-reference \n, where n is a single digit, matches the substring previously matched by the nth parenthesized subexpression of the regular expression. Basic vs Extended Regular Expressions In basic regular expressions the meta-characters ?, +, {, |, (, and ) lose their special meaning; instead use the backslashed versions \?, \+, \{, \|, \(, and \). EXIT STATUS top Normally the exit status is 0 if a line is selected, 1 if no lines were selected, and 2 if an error occurred. However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred. ENVIRONMENT top The behavior of grep is affected by the following environment variables. The locale for category LC_foo is specified by examining the three environment variables LC_ALL, LC_foo, LANG, in that order. The first of these variables that is set specifies the locale. For example, if LC_ALL is not set, but LC_MESSAGES is set to pt_BR, then the Brazilian Portuguese locale is used for the LC_MESSAGES category. The C locale is used if none of these environment variables are set, if the locale catalog is not installed, or if grep was not compiled with national language support (NLS). The shell command locale -a lists locales that are currently available. GREP_COLORS Controls how the --color option highlights output. Its value is a colon-separated list of capabilities that defaults to ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=36 with the rv and ne boolean capabilities omitted (i.e., false). Supported capabilities are as follows. sl= SGR substring for whole selected lines (i.e., matching lines when the -v command-line option is omitted, or non-matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to context matching lines instead. The default is empty (i.e., the terminal's default color pair). cx= SGR substring for whole context lines (i.e., non- matching lines when the -v command-line option is omitted, or matching lines when -v is specified). If however the boolean rv capability and the -v command-line option are both specified, it applies to selected non-matching lines instead. The default is empty (i.e., the terminal's default color pair). rv Boolean value that reverses (swaps) the meanings of the sl= and cx= capabilities when the -v command- line option is specified. The default is false (i.e., the capability is omitted). mt=01;31 SGR substring for matching non-empty text in any matching line (i.e., a selected line when the -v command-line option is omitted, or a context line when -v is specified). Setting this is equivalent to setting both ms= and mc= at once to the same value. The default is a bold red text foreground over the current line background. ms=01;31 SGR substring for matching non-empty text in a selected line. (This is only used when the -v command-line option is omitted.) The effect of the sl= (or cx= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. mc=01;31 SGR substring for matching non-empty text in a context line. (This is only used when the -v command-line option is specified.) The effect of the cx= (or sl= if rv) capability remains active when this kicks in. The default is a bold red text foreground over the current line background. fn=35 SGR substring for file names prefixing any content line. The default is a magenta text foreground over the terminal's default background. ln=32 SGR substring for line numbers prefixing any content line. The default is a green text foreground over the terminal's default background. bn=32 SGR substring for byte offsets prefixing any content line. The default is a green text foreground over the terminal's default background. se=36 SGR substring for separators that are inserted between selected line fields (:), between context line fields, (-), and between groups of adjacent lines when nonzero context is specified (--). The default is a cyan text foreground over the terminal's default background. ne Boolean value that prevents clearing to the end of line using Erase in Line (EL) to Right (\33[K) each time a colorized item ends. This is needed on terminals on which EL is not supported. It is otherwise useful on terminals for which the back_color_erase (bce) boolean terminfo capability does not apply, when the chosen highlight colors do not affect the background, or when EL is too slow or causes too much flicker. The default is false (i.e., the capability is omitted). Note that boolean capabilities have no =... part. They are omitted (i.e., false) by default and become true when specified. See the Select Graphic Rendition (SGR) section in the documentation of the text terminal that is used for permitted values and their meaning as character attributes. These substring values are integers in decimal representation and can be concatenated with semicolons. grep takes care of assembling the result into a complete SGR sequence (\33[...m). Common values to concatenate include 1 for bold, 4 for underline, 5 for blink, 7 for inverse, 39 for default foreground color, 30 to 37 for foreground colors, 90 to 97 for 16-color mode foreground colors, 38;5;0 to 38;5;255 for 88-color and 256-color modes foreground colors, 49 for default background color, 40 to 47 for background colors, 100 to 107 for 16-color mode background colors, and 48;5;0 to 48;5;255 for 88-color and 256-color modes background colors. LC_ALL, LC_COLLATE, LANG These variables specify the locale for the LC_COLLATE category, which determines the collating sequence used to interpret range expressions like [a-z]. LC_ALL, LC_CTYPE, LANG These variables specify the locale for the LC_CTYPE category, which determines the type of characters, e.g., which characters are whitespace. This category also determines the character encoding, that is, whether text is encoded in UTF-8, ASCII, or some other encoding. In the C or POSIX locale, all characters are encoded as a single byte and every byte is a valid character. LC_ALL, LC_MESSAGES, LANG These variables specify the locale for the LC_MESSAGES category, which determines the language that grep uses for messages. The default C locale uses American English messages. POSIXLY_CORRECT If set, grep behaves as POSIX requires; otherwise, grep behaves more like other GNU programs. POSIX requires that options that follow file names must be treated as file names; by default, such options are permuted to the front of the operand list and are treated as options. Also, POSIX requires that unrecognized options be diagnosed as illegal, but since they are not really against the law the default is to diagnose them as invalid. NOTES top This man page is maintained only fitfully; the full documentation is often more up-to-date. COPYRIGHT top Copyright 1998-2000, 2002, 2005-2023 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. BUGS top Reporting Bugs Email bug reports to the bug-reporting address bug- grep@gnu.org. An email archive https://lists.gnu.org/mailman/listinfo/bug-grep and a bug tracker https://debbugs.gnu.org/cgi/pkgreport.cgi?package=grep are available. Known Bugs Large repetition counts in the {n,m} construct may cause grep to use lots of memory. In addition, certain other obscure regular expressions require exponential time and space, and may cause grep to run out of memory. Back-references are very slow, and may require exponential time. EXAMPLE top The following example outputs the location and contents of any line containing f and ending in .c, within all files in the current directory whose names contain g and end in .h. The -n option outputs line numbers, the -- argument treats expansions of *g*.h starting with - as file names not options, and the empty file /dev/null causes file names to be output even if only one file name happens to be of the form *g*.h. $ grep -n -- 'f.*\.c$' *g*.h /dev/null argmatch.h:1:/* definitions and prototypes for argmatch.c The only line that matches is line 1 of argmatch.h. Note that the regular expression syntax used in the pattern differs from the globbing syntax that the shell uses to match file names. SEE ALSO top Regular Manual Pages awk(1), cmp(1), diff(1), find(1), perl(1), sed(1), sort(1), xargs(1), read(2), pcre2(3), pcre2syntax(3), pcre2pattern(3), terminfo(5), glob(7), regex(7) Full Documentation A complete manual https://www.gnu.org/software/grep/manual/ is available. If the info and grep programs are properly installed at your site, the command info grep should give you access to the complete manual. COLOPHON top This page is part of the GNU grep (regular expression file search tool) project. Information about the project can be found at https://www.gnu.org/software/grep/. If you have a bug report for this manual page, send it to bug-grep@gnu.org. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/grep.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-09-14.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU grep 3.11.21-102b-dirty 2019-12-29 GREP(1) Pages that refer to this page: look(1), pmrep(1), sed(1), regex(3), regex(7), bridge(8), ip(8), tc(8) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search in all the regular/normal files of the current folder for the word "word" and display the matched file name Bash Command:<START>find . -type f -exec grep -l "word" {} +<END>
search in current directory downwards all files whose size is less then 10 bytes
find . -size -10c -print
['find']
Output a Bash command to accomplish the following task. Task: search in current directory downwards all files whose size is less then 10 bytes Bash Command:<START>find . -size -10c -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search in current directory downwards all files whose size is less then 10 bytes Bash Command:<START>find . -size -10c -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search in current directory downwards all files whose size is less then 10 bytes Bash Command:<START>find . -size -10c -print<END>
search in the current directory for any file named Chapter1.txt
find . -name Chapter1 -type f
['find']
Output a Bash command to accomplish the following task. Task: search in the current directory for any file named Chapter1.txt Bash Command:<START>find . -name Chapter1 -type f<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search in the current directory for any file named Chapter1.txt Bash Command:<START>find . -name Chapter1 -type f<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search in the current directory for any file named Chapter1.txt Bash Command:<START>find . -name Chapter1 -type f<END>
search in the current folder for all the directories with the name "test"
find . -type d -name test
['find', 'test']
Output a Bash command to accomplish the following task. Task: search in the current folder for all the directories with the name "test" Bash Command:<START>find . -type d -name test<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # test\n\n> Check file types and compare values.\n> Returns 0 if the condition evaluates to true, 1 if it evaluates to false.\n> More information: <https://www.gnu.org/software/coreutils/test>.\n\n- Test if a given variable is equal to a given string:\n\n`test "{{$MY_VAR}}" = "{{/bin/zsh}}"`\n\n- Test if a given variable is empty:\n\n`test -z "{{$GIT_BRANCH}}"`\n\n- Test if a file exists:\n\n`test -f "{{path/to/file_or_directory}}"`\n\n- Test if a directory does not exist:\n\n`test ! -d "{{path/to/directory}}"`\n\n- If A is true, then do B, or C in the case of an error (notice that C may run even if A fails):\n\n`test {{condition}} && {{echo "true"}} || {{echo "false"}}`\n Task: search in the current folder for all the directories with the name "test" Bash Command:<START>find . -type d -name test<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. test(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training test(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TEST(1) User Commands TEST(1) NAME top test - check file types and compare values SYNOPSIS top test EXPRESSION test [ EXPRESSION ] [ ] [ OPTION DESCRIPTION top Exit with the status determined by EXPRESSION. --help display this help and exit --version output version information and exit An omitted EXPRESSION defaults to false. Otherwise, EXPRESSION is true or false and sets exit status. It is one of: ( EXPRESSION ) EXPRESSION is true ! EXPRESSION EXPRESSION is false EXPRESSION1 -a EXPRESSION2 both EXPRESSION1 and EXPRESSION2 are true EXPRESSION1 -o EXPRESSION2 either EXPRESSION1 or EXPRESSION2 is true -n STRING the length of STRING is nonzero STRING equivalent to -n STRING -z STRING the length of STRING is zero STRING1 = STRING2 the strings are equal STRING1 != STRING2 the strings are not equal INTEGER1 -eq INTEGER2 INTEGER1 is equal to INTEGER2 INTEGER1 -ge INTEGER2 INTEGER1 is greater than or equal to INTEGER2 INTEGER1 -gt INTEGER2 INTEGER1 is greater than INTEGER2 INTEGER1 -le INTEGER2 INTEGER1 is less than or equal to INTEGER2 INTEGER1 -lt INTEGER2 INTEGER1 is less than INTEGER2 INTEGER1 -ne INTEGER2 INTEGER1 is not equal to INTEGER2 FILE1 -ef FILE2 FILE1 and FILE2 have the same device and inode numbers FILE1 -nt FILE2 FILE1 is newer (modification date) than FILE2 FILE1 -ot FILE2 FILE1 is older than FILE2 -b FILE FILE exists and is block special -c FILE FILE exists and is character special -d FILE FILE exists and is a directory -e FILE FILE exists -f FILE FILE exists and is a regular file -g FILE FILE exists and is set-group-ID -G FILE FILE exists and is owned by the effective group ID -h FILE FILE exists and is a symbolic link (same as -L) -k FILE FILE exists and has its sticky bit set -L FILE FILE exists and is a symbolic link (same as -h) -N FILE FILE exists and has been modified since it was last read -O FILE FILE exists and is owned by the effective user ID -p FILE FILE exists and is a named pipe -r FILE FILE exists and the user has read access -s FILE FILE exists and has a size greater than zero -S FILE FILE exists and is a socket -t FD file descriptor FD is opened on a terminal -u FILE FILE exists and its set-user-ID bit is set -w FILE FILE exists and the user has write access -x FILE FILE exists and the user has execute (or search) access Except for -h and -L, all FILE-related tests dereference symbolic links. Beware that parentheses need to be escaped (e.g., by backslashes) for shells. INTEGER may also be -l STRING, which evaluates to the length of STRING. NOTE: Binary -a and -o are inherently ambiguous. Use 'test EXPR1 && test EXPR2' or 'test EXPR1 || test EXPR2' instead. NOTE: [ honors the --help and --version options, but test does not. test treats each of those as it treats any other nonempty STRING. NOTE: your shell may have its own version of test and/or [, which usually supersedes the version described here. Please refer to your shell's documentation for details about the options it supports. AUTHOR top Written by Kevin Braunsdorf and Matthew Bradburn. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top access(2) Full documentation <https://www.gnu.org/software/coreutils/test> or available locally via: info '(coreutils) test invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 TEST(1) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search in the current folder for all the directories with the name "test" Bash Command:<START>find . -type d -name test<END>
search in the current folder for all the regular/normal file with the name "test"
find . -type f -name test
['find', 'test']
Output a Bash command to accomplish the following task. Task: search in the current folder for all the regular/normal file with the name "test" Bash Command:<START>find . -type f -name test<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # test\n\n> Check file types and compare values.\n> Returns 0 if the condition evaluates to true, 1 if it evaluates to false.\n> More information: <https://www.gnu.org/software/coreutils/test>.\n\n- Test if a given variable is equal to a given string:\n\n`test "{{$MY_VAR}}" = "{{/bin/zsh}}"`\n\n- Test if a given variable is empty:\n\n`test -z "{{$GIT_BRANCH}}"`\n\n- Test if a file exists:\n\n`test -f "{{path/to/file_or_directory}}"`\n\n- Test if a directory does not exist:\n\n`test ! -d "{{path/to/directory}}"`\n\n- If A is true, then do B, or C in the case of an error (notice that C may run even if A fails):\n\n`test {{condition}} && {{echo "true"}} || {{echo "false"}}`\n Task: search in the current folder for all the regular/normal file with the name "test" Bash Command:<START>find . -type f -name test<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. test(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training test(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TEST(1) User Commands TEST(1) NAME top test - check file types and compare values SYNOPSIS top test EXPRESSION test [ EXPRESSION ] [ ] [ OPTION DESCRIPTION top Exit with the status determined by EXPRESSION. --help display this help and exit --version output version information and exit An omitted EXPRESSION defaults to false. Otherwise, EXPRESSION is true or false and sets exit status. It is one of: ( EXPRESSION ) EXPRESSION is true ! EXPRESSION EXPRESSION is false EXPRESSION1 -a EXPRESSION2 both EXPRESSION1 and EXPRESSION2 are true EXPRESSION1 -o EXPRESSION2 either EXPRESSION1 or EXPRESSION2 is true -n STRING the length of STRING is nonzero STRING equivalent to -n STRING -z STRING the length of STRING is zero STRING1 = STRING2 the strings are equal STRING1 != STRING2 the strings are not equal INTEGER1 -eq INTEGER2 INTEGER1 is equal to INTEGER2 INTEGER1 -ge INTEGER2 INTEGER1 is greater than or equal to INTEGER2 INTEGER1 -gt INTEGER2 INTEGER1 is greater than INTEGER2 INTEGER1 -le INTEGER2 INTEGER1 is less than or equal to INTEGER2 INTEGER1 -lt INTEGER2 INTEGER1 is less than INTEGER2 INTEGER1 -ne INTEGER2 INTEGER1 is not equal to INTEGER2 FILE1 -ef FILE2 FILE1 and FILE2 have the same device and inode numbers FILE1 -nt FILE2 FILE1 is newer (modification date) than FILE2 FILE1 -ot FILE2 FILE1 is older than FILE2 -b FILE FILE exists and is block special -c FILE FILE exists and is character special -d FILE FILE exists and is a directory -e FILE FILE exists -f FILE FILE exists and is a regular file -g FILE FILE exists and is set-group-ID -G FILE FILE exists and is owned by the effective group ID -h FILE FILE exists and is a symbolic link (same as -L) -k FILE FILE exists and has its sticky bit set -L FILE FILE exists and is a symbolic link (same as -h) -N FILE FILE exists and has been modified since it was last read -O FILE FILE exists and is owned by the effective user ID -p FILE FILE exists and is a named pipe -r FILE FILE exists and the user has read access -s FILE FILE exists and has a size greater than zero -S FILE FILE exists and is a socket -t FD file descriptor FD is opened on a terminal -u FILE FILE exists and its set-user-ID bit is set -w FILE FILE exists and the user has write access -x FILE FILE exists and the user has execute (or search) access Except for -h and -L, all FILE-related tests dereference symbolic links. Beware that parentheses need to be escaped (e.g., by backslashes) for shells. INTEGER may also be -l STRING, which evaluates to the length of STRING. NOTE: Binary -a and -o are inherently ambiguous. Use 'test EXPR1 && test EXPR2' or 'test EXPR1 || test EXPR2' instead. NOTE: [ honors the --help and --version options, but test does not. test treats each of those as it treats any other nonempty STRING. NOTE: your shell may have its own version of test and/or [, which usually supersedes the version described here. Please refer to your shell's documentation for details about the options it supports. AUTHOR top Written by Kevin Braunsdorf and Matthew Bradburn. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top access(2) Full documentation <https://www.gnu.org/software/coreutils/test> or available locally via: info '(coreutils) test invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 TEST(1) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search in the current folder for all the regular/normal file with the name "test" Bash Command:<START>find . -type f -name test<END>
search in the current folder for the file "myletter.doc"
find . -name myletter.doc -print
['find']
Output a Bash command to accomplish the following task. Task: search in the current folder for the file "myletter.doc" Bash Command:<START>find . -name myletter.doc -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search in the current folder for the file "myletter.doc" Bash Command:<START>find . -name myletter.doc -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search in the current folder for the file "myletter.doc" Bash Command:<START>find . -name myletter.doc -print<END>
search in the current folder for the file with the name "test"
find . -name test
['find', 'test']
Output a Bash command to accomplish the following task. Task: search in the current folder for the file with the name "test" Bash Command:<START>find . -name test<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # test\n\n> Check file types and compare values.\n> Returns 0 if the condition evaluates to true, 1 if it evaluates to false.\n> More information: <https://www.gnu.org/software/coreutils/test>.\n\n- Test if a given variable is equal to a given string:\n\n`test "{{$MY_VAR}}" = "{{/bin/zsh}}"`\n\n- Test if a given variable is empty:\n\n`test -z "{{$GIT_BRANCH}}"`\n\n- Test if a file exists:\n\n`test -f "{{path/to/file_or_directory}}"`\n\n- Test if a directory does not exist:\n\n`test ! -d "{{path/to/directory}}"`\n\n- If A is true, then do B, or C in the case of an error (notice that C may run even if A fails):\n\n`test {{condition}} && {{echo "true"}} || {{echo "false"}}`\n Task: search in the current folder for the file with the name "test" Bash Command:<START>find . -name test<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. test(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training test(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TEST(1) User Commands TEST(1) NAME top test - check file types and compare values SYNOPSIS top test EXPRESSION test [ EXPRESSION ] [ ] [ OPTION DESCRIPTION top Exit with the status determined by EXPRESSION. --help display this help and exit --version output version information and exit An omitted EXPRESSION defaults to false. Otherwise, EXPRESSION is true or false and sets exit status. It is one of: ( EXPRESSION ) EXPRESSION is true ! EXPRESSION EXPRESSION is false EXPRESSION1 -a EXPRESSION2 both EXPRESSION1 and EXPRESSION2 are true EXPRESSION1 -o EXPRESSION2 either EXPRESSION1 or EXPRESSION2 is true -n STRING the length of STRING is nonzero STRING equivalent to -n STRING -z STRING the length of STRING is zero STRING1 = STRING2 the strings are equal STRING1 != STRING2 the strings are not equal INTEGER1 -eq INTEGER2 INTEGER1 is equal to INTEGER2 INTEGER1 -ge INTEGER2 INTEGER1 is greater than or equal to INTEGER2 INTEGER1 -gt INTEGER2 INTEGER1 is greater than INTEGER2 INTEGER1 -le INTEGER2 INTEGER1 is less than or equal to INTEGER2 INTEGER1 -lt INTEGER2 INTEGER1 is less than INTEGER2 INTEGER1 -ne INTEGER2 INTEGER1 is not equal to INTEGER2 FILE1 -ef FILE2 FILE1 and FILE2 have the same device and inode numbers FILE1 -nt FILE2 FILE1 is newer (modification date) than FILE2 FILE1 -ot FILE2 FILE1 is older than FILE2 -b FILE FILE exists and is block special -c FILE FILE exists and is character special -d FILE FILE exists and is a directory -e FILE FILE exists -f FILE FILE exists and is a regular file -g FILE FILE exists and is set-group-ID -G FILE FILE exists and is owned by the effective group ID -h FILE FILE exists and is a symbolic link (same as -L) -k FILE FILE exists and has its sticky bit set -L FILE FILE exists and is a symbolic link (same as -h) -N FILE FILE exists and has been modified since it was last read -O FILE FILE exists and is owned by the effective user ID -p FILE FILE exists and is a named pipe -r FILE FILE exists and the user has read access -s FILE FILE exists and has a size greater than zero -S FILE FILE exists and is a socket -t FD file descriptor FD is opened on a terminal -u FILE FILE exists and its set-user-ID bit is set -w FILE FILE exists and the user has write access -x FILE FILE exists and the user has execute (or search) access Except for -h and -L, all FILE-related tests dereference symbolic links. Beware that parentheses need to be escaped (e.g., by backslashes) for shells. INTEGER may also be -l STRING, which evaluates to the length of STRING. NOTE: Binary -a and -o are inherently ambiguous. Use 'test EXPR1 && test EXPR2' or 'test EXPR1 || test EXPR2' instead. NOTE: [ honors the --help and --version options, but test does not. test treats each of those as it treats any other nonempty STRING. NOTE: your shell may have its own version of test and/or [, which usually supersedes the version described here. Please refer to your shell's documentation for details about the options it supports. AUTHOR top Written by Kevin Braunsdorf and Matthew Bradburn. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top access(2) Full documentation <https://www.gnu.org/software/coreutils/test> or available locally via: info '(coreutils) test invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 TEST(1) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search in the current folder for the file with the name "test" Bash Command:<START>find . -name test<END>
search in the current folder for the file with the name "test" ( case insensitive search )
find . -iname test
['find', 'test']
Output a Bash command to accomplish the following task. Task: search in the current folder for the file with the name "test" ( case insensitive search ) Bash Command:<START>find . -iname test<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n # test\n\n> Check file types and compare values.\n> Returns 0 if the condition evaluates to true, 1 if it evaluates to false.\n> More information: <https://www.gnu.org/software/coreutils/test>.\n\n- Test if a given variable is equal to a given string:\n\n`test "{{$MY_VAR}}" = "{{/bin/zsh}}"`\n\n- Test if a given variable is empty:\n\n`test -z "{{$GIT_BRANCH}}"`\n\n- Test if a file exists:\n\n`test -f "{{path/to/file_or_directory}}"`\n\n- Test if a directory does not exist:\n\n`test ! -d "{{path/to/directory}}"`\n\n- If A is true, then do B, or C in the case of an error (notice that C may run even if A fails):\n\n`test {{condition}} && {{echo "true"}} || {{echo "false"}}`\n Task: search in the current folder for the file with the name "test" ( case insensitive search ) Bash Command:<START>find . -iname test<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. test(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training test(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | AUTHOR | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON TEST(1) User Commands TEST(1) NAME top test - check file types and compare values SYNOPSIS top test EXPRESSION test [ EXPRESSION ] [ ] [ OPTION DESCRIPTION top Exit with the status determined by EXPRESSION. --help display this help and exit --version output version information and exit An omitted EXPRESSION defaults to false. Otherwise, EXPRESSION is true or false and sets exit status. It is one of: ( EXPRESSION ) EXPRESSION is true ! EXPRESSION EXPRESSION is false EXPRESSION1 -a EXPRESSION2 both EXPRESSION1 and EXPRESSION2 are true EXPRESSION1 -o EXPRESSION2 either EXPRESSION1 or EXPRESSION2 is true -n STRING the length of STRING is nonzero STRING equivalent to -n STRING -z STRING the length of STRING is zero STRING1 = STRING2 the strings are equal STRING1 != STRING2 the strings are not equal INTEGER1 -eq INTEGER2 INTEGER1 is equal to INTEGER2 INTEGER1 -ge INTEGER2 INTEGER1 is greater than or equal to INTEGER2 INTEGER1 -gt INTEGER2 INTEGER1 is greater than INTEGER2 INTEGER1 -le INTEGER2 INTEGER1 is less than or equal to INTEGER2 INTEGER1 -lt INTEGER2 INTEGER1 is less than INTEGER2 INTEGER1 -ne INTEGER2 INTEGER1 is not equal to INTEGER2 FILE1 -ef FILE2 FILE1 and FILE2 have the same device and inode numbers FILE1 -nt FILE2 FILE1 is newer (modification date) than FILE2 FILE1 -ot FILE2 FILE1 is older than FILE2 -b FILE FILE exists and is block special -c FILE FILE exists and is character special -d FILE FILE exists and is a directory -e FILE FILE exists -f FILE FILE exists and is a regular file -g FILE FILE exists and is set-group-ID -G FILE FILE exists and is owned by the effective group ID -h FILE FILE exists and is a symbolic link (same as -L) -k FILE FILE exists and has its sticky bit set -L FILE FILE exists and is a symbolic link (same as -h) -N FILE FILE exists and has been modified since it was last read -O FILE FILE exists and is owned by the effective user ID -p FILE FILE exists and is a named pipe -r FILE FILE exists and the user has read access -s FILE FILE exists and has a size greater than zero -S FILE FILE exists and is a socket -t FD file descriptor FD is opened on a terminal -u FILE FILE exists and its set-user-ID bit is set -w FILE FILE exists and the user has write access -x FILE FILE exists and the user has execute (or search) access Except for -h and -L, all FILE-related tests dereference symbolic links. Beware that parentheses need to be escaped (e.g., by backslashes) for shells. INTEGER may also be -l STRING, which evaluates to the length of STRING. NOTE: Binary -a and -o are inherently ambiguous. Use 'test EXPR1 && test EXPR2' or 'test EXPR1 || test EXPR2' instead. NOTE: [ honors the --help and --version options, but test does not. test treats each of those as it treats any other nonempty STRING. NOTE: your shell may have its own version of test and/or [, which usually supersedes the version described here. Please refer to your shell's documentation for details about the options it supports. AUTHOR top Written by Kevin Braunsdorf and Matthew Bradburn. REPORTING BUGS top GNU coreutils online help: <https://www.gnu.org/software/coreutils/> Report any translation bugs to <https://translationproject.org/team/> COPYRIGHT top Copyright 2023 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 top access(2) Full documentation <https://www.gnu.org/software/coreutils/test> or available locally via: info '(coreutils) test invocation' COLOPHON top This page is part of the coreutils (basic file, shell and text manipulation utilities) project. Information about the project can be found at http://www.gnu.org/software/coreutils/. If you have a bug report for this manual page, see http://www.gnu.org/software/coreutils/. This page was obtained from the tarball coreutils-9.4.tar.xz fetched from http://ftp.gnu.org/gnu/coreutils/ on 2023-12-22. If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org GNU coreutils 9.4 August 2023 TEST(1) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search in the current folder for the file with the name "test" ( case insensitive search ) Bash Command:<START>find . -iname test<END>
search in the current folder for the files that begin with "myletter"
find . -name 'myletter*' -print
['find']
Output a Bash command to accomplish the following task. Task: search in the current folder for the files that begin with "myletter" Bash Command:<START>find . -name 'myletter*' -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search in the current folder for the files that begin with "myletter" Bash Command:<START>find . -name 'myletter*' -print<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search in the current folder for the files that begin with "myletter" Bash Command:<START>find . -name 'myletter*' -print<END>
search in the home folder for all the files with the name "monfichier"
find /home/ -name monfichier
['find']
Output a Bash command to accomplish the following task. Task: search in the home folder for all the files with the name "monfichier" Bash Command:<START>find /home/ -name monfichier<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: # find\n\n> Find files or directories under a directory tree, recursively.\n> More information: <https://manned.org/find>.\n\n- Find files by extension:\n\n`find {{root_path}} -name '{{*.ext}}'`\n\n- Find files matching multiple path/name patterns:\n\n`find {{root_path}} -path '{{**/path/**/*.ext}}' -or -name '{{*pattern*}}'`\n\n- Find directories matching a given name, in case-insensitive mode:\n\n`find {{root_path}} -type d -iname '{{*lib*}}'`\n\n- Find files matching a given pattern, excluding specific paths:\n\n`find {{root_path}} -name '{{*.py}}' -not -path '{{*/site-packages/*}}'`\n\n- Find files matching a given size range, limiting the recursive depth to "1":\n\n`find {{root_path}} -maxdepth 1 -size {{+500k}} -size {{-10M}}`\n\n- Run a command for each file (use `{}` within the command to access the filename):\n\n`find {{root_path}} -name '{{*.ext}}' -exec {{wc -l}} {} \;`\n\n- Find all files modified today and pass the results to a single command as arguments:\n\n`find {{root_path}} -daystart -mtime {{-1}} -exec {{tar -cvf archive.tar}} {} \+`\n\n- Find empty (0 byte) files and delete them:\n\n`find {{root_path}} -type {{f}} -empty -delete`\n Task: search in the home folder for all the files with the name "monfichier" Bash Command:<START>find /home/ -name monfichier<END>
Use the provided context to output a Bash command that accomplishes the following task. Context: find(1) - Linux manual page man7.org > Linux > man-pages Linux/UNIX system programming training find(1) Linux manual page NAME | SYNOPSIS | DESCRIPTION | OPTIONS | EXPRESSION | UNUSUAL FILENAMES | STANDARDS CONFORMANCE | ENVIRONMENT VARIABLES | EXAMPLES | EXIT STATUS | HISTORY | COMPATIBILITY | NON-BUGS | BUGS | REPORTING BUGS | COPYRIGHT | SEE ALSO | COLOPHON FIND(1) General Commands Manual FIND(1) NAME top find - search for files in a directory hierarchy SYNOPSIS top find [-H] [-L] [-P] [-D debugopts] [-Olevel] [starting-point...] [expression] DESCRIPTION top This manual page documents the GNU version of find. GNU find searches the directory tree rooted at each given starting-point by evaluating the given expression from left to right, according to the rules of precedence (see section OPERATORS), until the outcome is known (the left hand side is false for and operations, true for or), at which point find moves on to the next file name. If no starting-point is specified, `.' is assumed. If you are using find in an environment where security is important (for example if you are using it to search directories that are writable by other users), you should read the `Security Considerations' chapter of the findutils documentation, which is called Finding Files and comes with findutils. That document also includes a lot more detail and discussion than this manual page, so you may find it a more useful source of information. OPTIONS top The -H, -L and -P options control the treatment of symbolic links. Command-line arguments following these are taken to be names of files or directories to be examined, up to the first argument that begins with `-', or the argument `(' or `!'. That argument and any following arguments are taken to be the expression describing what is to be searched for. If no paths are given, the current directory is used. If no expression is given, the expression -print is used (but you should probably consider using -print0 instead, anyway). This manual page talks about `options' within the expression list. These options control the behaviour of find but are specified 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. When find examines or prints information about files, and the file is a symbolic link, the information used shall be taken from the properties of the symbolic link itself. -L Follow symbolic links. When find examines or prints information about files, the information used shall be taken from the properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the 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. When find examines 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 -H is in effect and one of the paths specified on the command line is a symbolic link to a directory, the contents of that directory will be examined (though of course -maxdepth 0 would prevent this). If more than one of -H, -L and -P is specified, each overrides the 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. 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). -D debugopts Print diagnostic information; this can be helpful to diagnose problems with why find is not doing what you want. The list of debug options should be comma separated. Compatibility of the debug options is not guaranteed between releases of findutils. For a complete list of valid debug options, see the output of find -D help. Valid debug options include exec Show diagnostic information relating to -exec, -execdir, -ok and -okdir opt Prints diagnostic information relating to the optimisation of the expression tree; see the -O option. 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 the stat and lstat system calls. The find program tries to minimise such calls. tree Show the expression tree in its original and optimised form. all Enable all of the other debug options (but help). help Explain the debugging options. -Olevel Enables query optimisation. The find program reorders tests to speed up execution while preserving the overall effect; that is, predicates with side effects are not reordered relative to each other. The optimisations performed at each optimisation level are as follows. 0 Equivalent to optimisation level 1. 1 This is the default optimisation level and corresponds to the traditional behaviour. Expressions are reordered so that tests based only on the names of files (for example -name and -regex) are performed first. 2 Any -type or -xtype tests are performed after any tests based only on the names of files, but before any tests that require information from the inode. On many modern versions of Unix, file types are returned by readdir() and so these predicates are faster to evaluate than predicates which need to stat the file first. If you use the -fstype FOO predicate and specify a filesystem type FOO which is not known (that is, present in `/etc/mtab') at the time find starts, that predicate is equivalent to -false. 3 At this optimisation level, the full cost-based query optimiser 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 optimiser has a fixed idea of how likely any given test is to succeed. In some cases the probability takes account of the specific nature of the test (for example, -type f is assumed to be more likely to succeed than -type c). The cost-based optimiser is currently being evaluated. If it does not actually improve the performance of find, it will be removed again. Conversely, optimisations that prove to be reliable, 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. EXPRESSION top 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 -empty test 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 -print action for example prints the name of the current file on the standard output. Global options Global options affect the operation of tests and actions specified on any part of the command line. Global options always return true. The -depth option for example makes find traverse the file system in a depth-first order. Positional options Positional options affect only tests or actions which follow them. Positional options always return true. The -regextype option for example is positional, specifying the regular expression dialect for regular expressions occurring later on the command line. Operators Operators join together the other items within the expression. They include for example -o (meaning logical OR) and -a (meaning logical AND). Where an operator is missing, -a is assumed. The -print action is performed on all files for which the whole expression is true, unless it contains an action other than -prune or -quit. Actions which inhibit the default -print are -delete, -exec, -execdir, -ok, -okdir, -fls, -fprint, -fprintf, -ls, -print and -printf. The -delete action also acts like an option (since it implies -depth). POSITIONAL OPTIONS Positional options always return true. They affect only tests occurring later on the command line. -daystart Measure times (for -amin, -atime, -cmin, -ctime, -mmin, and -mtime) from the beginning of today rather than from 24 hours ago. This option only affects tests which appear later on the command line. -follow Deprecated; use the -L option instead. Dereference symbolic links. Implies -noleaf. The -follow option affects only those tests which appear after it on the command line. Unless the -H or -L option has been specified, the position of the -follow option changes the behaviour of the -newer predicate; any files listed as the argument of -newer will be dereferenced if they are symbolic links. The same consideration applies to -newerXY, -anewer and -cnewer. Similarly, the -type predicate will always match against the type of the file that a symbolic link points to rather than the link itself. Using -follow causes the -lname and -ilname predicates always to return false. -regextype type Changes the regular expression syntax understood by -regex and -iregex tests which occur later on the command line. To see which regular expression types are known, use -regextype help. The Texinfo documentation (see SEE ALSO) explains the meaning of and differences between the various types of regular expression. -warn, -nowarn Turn warning messages on or off. These warnings apply only to the command line usage, not to any conditions that find might encounter when it searches directories. The default behaviour corresponds to -warn if standard input is a tty, and to -nowarn otherwise. If a warning message relating to command-line usage is produced, the exit status of find is not affected. If the POSIXLY_CORRECT environment variable is set, and -warn is also used, it is not specified which, if any, warnings will be active. GLOBAL OPTIONS Global options always return true. Global options take effect even for tests which occur earlier on the command line. To prevent confusion, global options should 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. -d A synonym for -depth, for compatibility with FreeBSD, NetBSD, MacOS X and OpenBSD. -depth Process each directory's contents before the directory itself. The -delete action also implies -depth. -files0-from file Read the starting points from file instead of getting them on the command line. In contrast to the known limitations of passing starting points via arguments on the command line, namely the limitation of the amount of file names, and the inherent ambiguity of file names clashing with option names, using this option allows to safely pass an arbitrary number of starting points to find. Using this option and passing starting points on the command line is mutually exclusive, and is therefore not allowed at the same time. The file argument is mandatory. One can use -files0-from - to read the list of starting points from the standard input stream, and e.g. from a pipe. In this case, the actions -ok and -okdir are not allowed, because they would obviously interfere with reading from standard input in order to get a user confirmation. The starting points in file have to be separated by ASCII NUL characters. Two consecutive NUL characters, i.e., a starting point with a Zero-length file name is not allowed and will lead to an error diagnostic followed by a non- Zero exit code later. In the case the given file is empty, find does not process any starting point and therefore will exit immediately after parsing the program arguments. This is unlike the standard invocation where find assumes the current directory as starting point if no path argument is passed. The processing of the starting points is otherwise as usual, e.g. find will recurse into subdirectories unless otherwise prevented. To process only the starting points, one can additionally pass -maxdepth 0. Further notes: if a file is listed more than once in the input file, it is unspecified whether it is visited more than once. If the file is mutated during the operation of find, the result is unspecified as well. Finally, the seek position within the named file at the time find exits, be it with -quit or in any other way, is also unspecified. By "unspecified" here is meant that it may or may not work or do any specific thing, and that the behavior may change from platform to platform, or from findutils release to release. -help, --help Print a summary of the command-line usage of find and exit. -ignore_readdir_race Normally, find will emit an error message when it fails to stat a file. If you give this option and a file is deleted between the time find reads the name of the file from the directory and the time it tries to stat the file, no error message will be 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 two find commands 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 0 means only apply the tests and actions to the starting- points themselves. -mindepth levels Do not apply any tests or actions at levels less than levels (a non-negative integer). Using -mindepth 1 means process all files except the starting-points. -mount Don't descend directories on other filesystems. An alternate name for -xdev, for compatibility with some other versions of find. -noignore_readdir_race Turns off the effect of -ignore_readdir_race. -noleaf Do not optimize by assuming that directories contain 2 fewer subdirectories than their hard link count. This option is needed when searching filesystems that do not follow the Unix directory-link convention, such as CD-ROM or MS-DOS filesystems or AFS volume mount points. Each directory on a normal Unix filesystem has at least 2 hard links: its name and its `.' entry. Additionally, its subdirectories (if any) each have a `..' entry linked to that directory. When find is examining a directory, after it has statted 2 fewer subdirectories than the directory's link count, it knows that the rest of the entries in the directory are non-directories (`leaf' files in the directory tree). If only the files' names need to be examined, there is no need to stat them; this gives a significant increase in search speed. -version, --version Print the find version number and exit. -xdev Don't descend directories on other filesystems. TESTS Some tests, for example -newerXY and -samefile, allow comparison 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 Time of the last access of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -atime n File was last accessed less than, more than or exactly n*24 hours ago. When find figures out how many 24-hour periods ago the file was last accessed, any fractional part is ignored, so to match -atime +1, a file has to have been accessed at least two days ago. -cmin n File's status was last changed less than, more than or exactly n minutes ago. -cnewer reference Time of the last status change of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -ctime n File's status was last changed less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file status change times. -empty File is empty and is either a regular file or a directory. -executable Matches files which are executable and directories which are searchable (in a file name resolution sense) by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root-squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. Because this test is based only on the result of the access(2) system call, there is no guarantee that a file for which this test succeeds can actually be executed. -false Always false. -fstype type File is on a filesystem of type type. The valid filesystem types vary among different versions of Unix; an incomplete list of filesystem types that are accepted on some version of Unix or another is: ufs, 4.2, 4.3, nfs, tmp, mfs, S51K, S52K. You can use -printf with the %F directive to see the types of your filesystems. -gid n File's numeric group ID is less than, more than or exactly n. -group gname File belongs to group gname (numeric group ID allowed). -ilname pattern Like -lname, but the match is case insensitive. If the -L option or the -follow option is in effect, this test returns false unless the symbolic link is broken. -iname pattern Like -name, but the match is case insensitive. For example, the patterns `fo*' and `F??' match the file names `Foo', `FOO', `foo', `fOo', etc. The pattern `*foo*` will also match a file called '.foobar'. -inum n File has inode number smaller than, greater than or exactly n. It is normally easier to use the -samefile test instead. -ipath pattern Like -path. but the match is case insensitive. -iregex pattern Like -regex, but the match is case insensitive. -iwholename pattern See -ipath. This alternative is less portable than -ipath. -links n File has less than, more than or exactly n hard links. -lname pattern File is a symbolic link whose contents match shell pattern pattern. The metacharacters do not treat `/' or `.' specially. If the -L option or the -follow option 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 exactly n minutes ago. -mtime n File's data was last modified less than, more than or exactly n*24 hours ago. See the comments for -atime to understand how rounding affects the interpretation of file modification times. -name pattern Base of file name (the path with the leading directories removed) matches shell pattern pattern. Because the leading directories of the file names are removed, the pattern should not include a slash, because `-name a/b' will never match anything (and you probably want to use -path instead). An exception to this is when using only a slash as pattern (`-name /'), because that is a valid string for matching the root directory "/" (because the base name of "/" is "/"). A warning is issued if you try to pass a pattern containing a - but not consisting solely of one - slash, unless the environment variable POSIXLY_CORRECT is set or the option -nowarn is used. To ignore a directory and the files under it, use -prune rather than checking every file in the tree; see an example in the description of that action. Braces are not recognised as being special, despite the fact that some shells including Bash imbue braces with a special meaning in shell patterns. The filename matching is performed with the use of the fnmatch(3) library function. Don't forget to enclose the pattern in quotes in order to protect it from expansion by the shell. -newer reference Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the -H option or the -L option is in effect, then the time of the last data modification of the file it points to is always used. -newerXY reference Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters: a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time Some combinations are invalid; for example, it is invalid for X to be t. Some combinations are not implemented on all systems; for example B is not supported on all systems. If an invalid or unsupported combination of XY is specified, a fatal error results. Time specifications are interpreted as for the argument to the -d option of GNU date. If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results. If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown. -nogroup No group corresponds to file's numeric group ID. -nouser No user corresponds to file's numeric user ID. -path pattern File name matches shell pattern pattern. The metacharacters do not treat `/' or `.' specially; so, for example, find . -path "./sr*sc" will print an entry for a directory called ./src/misc (if one exists). To ignore a whole directory tree, use -prune rather than checking every file in the tree. Note that the pattern match test applies to the whole file name, starting from one of the start points named on the command line. It would only make sense to use an absolute path name here if the relevant start point is also an absolute path. This means that this command will never match anything: find bar -path /foo/bar/myfile -print Find compares the -path argument with the concatenation of a directory name and the base name of the file it's examining. Since the concatenation will never end with a slash, -path arguments ending in a slash will match nothing (except perhaps a start point specified on the command line). The predicate -path is also supported by HP-UX find and is part of the POSIX 2008 standard. -perm mode File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example `-perm g=w' will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example `-perm -g=w', which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which you would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode This is no longer supported (and has been deprecated since 2005). Use -perm /mode instead. -readable Matches files which are readable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -regex pattern File name matches regular expression pattern. This is a match on the whole path, not a search. For example, to match a file named ./fubar3, you can use the regular expression `.*bar.' or `.*b.*3', but not `f.*r3'. The regular expressions understood by find are by default Emacs Regular Expressions (except that `.' matches newline), but this can be changed with the -regextype option. -samefile name File refers to the same inode as name. When -L is in effect, this can include symbolic links. -size n[cwbkMG] File uses less than, more than or exactly n units of space, rounding up. The following suffixes can be used: `b' for 512-byte blocks (this is the default if no suffix is used) `c' for bytes `w' for two-byte words `k' for kibibytes (KiB, units of 1024 bytes) `M' for mebibytes (MiB, units of 1024 * 1024 = 1048576 bytes) `G' for gibibytes (GiB, units of 1024 * 1024 * 1024 = 1073741824 bytes) The size is simply the st_size member of the struct stat populated by the lstat (or stat) system call, rounded up as shown above. In other words, it's consistent with the result you get for ls -l. Bear in mind that the `%k' and `%b' format specifiers of -printf handle sparse files differently. The `b' suffix always denotes 512-byte blocks and never 1024-byte blocks, which is different to the behaviour of -ls. The + and - prefixes signify greater than and less than, as usual; i.e., an exact size of n units does not match. Bear in mind that the size is rounded up to the next unit. Therefore -size -1M is not equivalent to -size -1048576c. The former only matches empty files, the latter matches files from 0 to 1,048,575 bytes. -true Always true. -type c File is of type c: b block (buffered) special c character (unbuffered) special d directory p named pipe (FIFO) f regular file l symbolic link; this is never true if the -L option or the -follow option is in effect, unless the symbolic link is broken. If you want to search for symbolic links when -L is in effect, use -xtype. s socket D door (Solaris) To search for more than one type at once, you can supply the combined list of type letters separated by a comma `,' (GNU extension). -uid n File's numeric user ID is less than, more than or exactly n. -used n File was last accessed less than, more than or exactly n days after its status was last changed. -user uname File is owned by user uname (numeric user ID allowed). -wholename pattern See -path. This alternative is less portable than -path. -writable Matches files which are writable by the current user. This takes into account access control lists and other permissions artefacts which the -perm test ignores. This test makes use of the access(2) system call, and so can be fooled by NFS servers which do UID mapping (or root- squashing), since many systems implement access(2) in the client's kernel and so cannot make use of the UID mapping information held on the server. -xtype c The same as -type unless the file is a symbolic link. For symbolic links: if the -H or -P option was specified, true if the file is a link to a file of type c; if the -L option has been given, true if c is `l'. In other words, for symbolic links, -xtype checks the type of the file that -type does not check. -context pattern (SELinux only) Security context of the file matches glob pattern. ACTIONS -delete Delete files or directories; true if removal succeeded. If the removal failed, an error message is issued and find's exit status will be nonzero (when it eventually exits). Warning: Don't forget that find evaluates the command line as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. The use of the -delete action on the command line automatically turns on the -depth option. As in turn -depth makes -prune ineffective, the -delete action cannot usefully be combined with -prune. Often, the user might want to test a find command line with -print prior to adding -delete for the actual removal run. To avoid surprising results, it is usually best to remember to use -depth explicitly during those earlier test runs. The -delete action will fail to remove a directory unless it is empty. Together with the -ignore_readdir_race option, find will ignore errors of the -delete action in the case the file has disappeared since the parent directory was read: it will not output an error diagnostic, not change the exit code to nonzero, and the return code of the -delete action will be true. -exec command ; Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of `;' is encountered. The string `{}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `\') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead. -exec command {} + This variant of the -exec action runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of `{}' is allowed within the command, and it must appear at the end, immediately before the `+'; it needs to be escaped (with a `\') or quoted to protect it from interpretation by the shell. The command is executed in the starting directory. If any 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 ... {} + -quit may not result in my-command actually being run. This variant of -exec always returns true. -execdir command ; -execdir command {} + 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. As with -exec, the {} should be quoted if find is being invoked from a shell. This a much more secure method for invoking commands, as it avoids race conditions during resolution of the paths to the matched files. As with the -exec action, the `+' form of -execdir will build a command line to process more than one matched file, but any given invocation of command will only list files that exist in the same subdirectory. If you use this option, you must ensure that your PATH environment variable does not reference `.'; 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 in PATH which 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, while -execdir command {} ; returns true only if command returns 0. -fls file True; like -ls but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprint file True; print the full file name into file file. If file does not exist when find is run, it is created; if it does exist, it is truncated. The file names /dev/stdout and /dev/stderr are 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. -fprint0 file True; like -print0 but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -fprintf file format True; like -printf but write to file like -fprint. The output file is always created, even if the predicate is never matched. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ls True; list current file in ls -dils format on standard output. The block counts are of 1 KB blocks, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -ok command ; Like -exec but ask the user first. If the user agrees, run the command. Otherwise just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. The response to the prompt is matched against a pair of regular expressions to determine if it is an affirmative or negative response. This regular expression is obtained from the system if the POSIXLY_CORRECT environment variable is set, or otherwise from find's message translations. If the system has no suitable definition, find's own definition will be used. In either case, the interpretation of the regular expression itself will be affected by the environment variables LC_CTYPE (character classes) and LC_COLLATE (character ranges and equivalence classes). -okdir command ; Like -execdir but ask the user first in the same way as for -ok. If the user does not agree, just return false. If the command is run, its standard input is redirected from /dev/null. This action may not be specified together with the -files0-from option. -print True; print the full file name on the standard output, followed by a newline. If you are piping the output of find into another program and there is the faintest possibility that the files which you are searching for might contain a newline, then you should seriously consider using the -print0 option instead of -print. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -print0 True; print the full file name on the standard output, followed by a null character (instead of the newline character that -print uses). This allows file names that contain newlines or other types of white space to be correctly interpreted by programs that process the find output. This option corresponds to the -0 option of xargs. -printf format True; print format on the standard output, interpreting `\' escapes and `%' directives. Field widths and precisions can be specified as with the printf(3) C function. Please note that many of the fields are printed as %s rather than %d, and this may mean that flags don't work as you might expect. This also means that the `-' flag does work (it forces fields to be left-aligned). Unlike -print, -printf does not add a newline at the end of the string. The escapes and directives are: \a Alarm bell. \b Backspace. \c Stop printing from this format immediately and flush the output. \f Form feed. \n Newline. \r Carriage return. \t Horizontal tab. \v Vertical tab. \0 ASCII NUL. \\ A literal backslash (`\'). \NNN The character whose ASCII code is NNN (octal). A `\' character followed by any other character is treated as an ordinary character, so they both are printed. %% A literal percent sign. %a File's last access time in the format returned by the C ctime(3) function. %Ak File's last access time in the format specified by k, which is either `@' or a directive for the C strftime(3) function. The following shows an incomplete list of possible values for k. Please refer to the documentation of strftime(3) for the full list. Some of the conversion specification characters might not be available on all systems, due to differences in the implementation of the strftime(3) library function. @ seconds since Jan. 1, 1970, 00:00 GMT, with fractional part. Time fields: H hour (00..23) I hour (01..12) k hour ( 0..23) l hour ( 1..12) M minute (00..59) p locale's AM or PM r time, 12-hour (hh:mm:ss [AP]M) S Second (00.00 .. 61.00). There is a fractional part. T time, 24-hour (hh:mm:ss.xxxxxxxxxx) + Date and time, separated by `+', for example `2004-04-28+22:22:05.0'. This is a GNU extension. The time is given in the current timezone (which may be affected by setting the TZ environment variable). The seconds field includes a fractional part. X locale's time representation (H:M:S). The seconds field includes a fractional part. Z time zone (e.g., EDT), or nothing if no time zone is determinable Date fields: a locale's abbreviated weekday name (Sun..Sat) A locale's full weekday name, variable length (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 for ctime(3) and so to preserve compatibility with that format, there is no fractional part in the seconds field. d day of month (01..31) D date (mm/dd/yy) F date (yyyy-mm-dd) h same as b j day of year (001..366) m month (01..12) U week number of year with Sunday as first day of week (00..53) w day of week (0..6) W week number of year with Monday as first day of week (00..53) x locale's date representation (mm/dd/yy) y last two digits of year (00..99) Y year (1970...) %b The amount of disk space used for this file in 512-byte blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/512, but it can also be smaller if the file is a sparse file. %Bk File's birth time, i.e., its creation time, in the format specified by k, which is the same as for %A. This directive produces an empty string if the underlying operating system or filesystem does not support birth times. %c File's last status change time in the format returned by the C ctime(3) function. %Ck File's last status change time in the format specified by k, which is the same as for %A. %d File's depth in the directory tree; 0 means the file is a starting-point. %D The device number on which the file exists (the st_dev field of struct stat), in decimal. %f Print the basename; the file's name with any leading directories removed (only the last element). For /, the result is `/'. See the EXAMPLES section for an example. %F Type of the filesystem the file is on; this value can be used for -fstype. %g File's group name, or numeric group ID if the group has no name. %G File's numeric group ID. %h Dirname; the Leading directories of the file's name (all but the last element). If the file name contains no slashes (since it is in the current directory) the %h specifier expands to `.'. For files which are themselves directories and contain a slash (including /), %h expands to the empty string. See the EXAMPLES section for an example. %H Starting-point under which file was found. %i File's inode number (in decimal). %k The amount of disk space used for this file in 1 KB blocks. Since disk space is allocated in multiples of the filesystem block size this is usually greater than %s/1024, but it can also be smaller if the file is a sparse file. %l Object of symbolic link (empty string if file is not a symbolic link). %m File's permission bits (in octal). This option uses the `traditional' numbers which most Unix implementations use, but if your particular implementation uses an unusual ordering of octal permissions bits, you will see a difference between the actual value of the file's mode and the output of %m. Normally you will want to have a leading zero on this number, and to do this, you should use the # flag (as in, for example, `%#m'). %M File's permissions (in symbolic form, as for ls). This directive is supported in findutils 4.2.5 and later. %n Number of hard links to file. %p File's name. %P File's name with the name of the starting-point under which it was found removed. %s File's size in bytes. %S File's sparseness. This is calculated as (BLOCKSIZE*st_blocks / st_size). The exact value you will get for an ordinary file of a certain length is system-dependent. However, normally sparse files will have values less than 1.0, and files which use indirect blocks may have a value which is greater than 1.0. In general the number of blocks used by a file is file system dependent. The value used for BLOCKSIZE is system-dependent, but is usually 512 bytes. If the file size is zero, the value printed is undefined. On systems which lack support for st_blocks, a file's sparseness is assumed to be 1.0. %t File's last modification time in the format returned by the C ctime(3) function. %Tk File's last modification time in the format specified by k, which is the same as for %A. %u File's user name, or numeric user ID if the user has no name. %U File's numeric user ID. %y File's type (like in ls -l), U=unknown type (shouldn't happen) %Y File's type (like %y), plus follow symbolic links: `L'=loop, `N'=nonexistent, `?' for any other error when determining the type of the target of a symbolic link. %Z (SELinux only) file's security context. %{ %[ %( Reserved for future use. A `%' character followed by any other character is discarded, but the other character is printed (don't rely on this, as further format characters may be introduced). A `%' at the end of the format argument causes undefined behaviour since there is no following character. In some locales, it may hide your door keys, while in others it may remove the final page from the novel you are reading. The %m and %d directives support the #, 0 and + flags, but the other directives do not, even if they print numbers. Numeric directives that do not support these flags include G, U, b, D, k and n. The `-' format flag is supported and changes the alignment of a field from right-justified (which is the default) to left-justified. See the UNUSUAL FILENAMES section for information about how unusual characters in filenames are handled. -prune True; if the file is a directory, do not descend into it. If -depth is given, then -prune has no effect. Because -delete implies -depth, you cannot usefully use -prune and -delete together. For example, to skip the directory src/emacs and all files and directories under it, and print the names of the other files found, do something like this: find . -path ./src/emacs -prune -o -print -quit Exit immediately (with return value zero if no errors have occurred). This is different to -prune because -prune only applies to the contents of pruned directories, while -quit simply makes find stop immediately. No child processes will be left running. Any command lines which have been built by -exec ... + or -execdir ... + are invoked before the program is exited. After -quit is executed, no more files specified on the command line will be processed. For example, `find /tmp/foo /tmp/bar -print -quit` will print only `/tmp/foo`. One common use of -quit is to stop searching the file system once we have found what we want. For example, if we want to find just a single file we can do this: find / -name needle -print -quit OPERATORS Listed in order of decreasing precedence: ( expr ) Force precedence. Since parentheses are special to the shell, you will normally need to quote them. Many of the examples in this manual page use backslashes for this purpose: `\(...\)' instead of `(...)'. ! expr True if expr is false. This character will also usually need protection from interpretation by the shell. -not expr Same as ! expr, but not POSIX compliant. expr1 expr2 Two expressions in a row are taken to be joined with an implied -a; expr2 is not evaluated if expr1 is false. expr1 -a expr2 Same as expr1 expr2. expr1 -and expr2 Same as expr1 expr2, but not POSIX compliant. expr1 -o expr2 Or; expr2 is not evaluated if expr1 is true. expr1 -or expr2 Same as expr1 -o expr2, but not POSIX compliant. expr1 , expr2 List; both expr1 and expr2 are always evaluated. The value of expr1 is discarded; the value of the list is the value of expr2. The comma operator can be useful for searching for several different types of thing, but traversing the filesystem hierarchy only once. The -fprintf action can be used to list the various matched items into several different output files. Please note that -a when specified implicitly (for example by two tests appearing without an explicit operator between them) or explicitly has higher precedence than -o. This means that find . -name afile -o -name bfile -print will never print afile. UNUSUAL FILENAMES top Many of the actions of find result in the printing of data which is under the control of other users. This includes file names, sizes, modification times and so forth. File names are a potential problem since they can contain any character except `\0' and `/'. Unusual characters in file names can do unexpected and often undesirable things to your terminal (for example, changing the settings of your function keys on some terminals). Unusual characters are handled differently by various actions, as described below. -print0, -fprint0 Always print the exact filename, unchanged, even if the output is going to a terminal. -ls, -fls Unusual characters are always escaped. White space, backslash, and double quote characters are printed using C-style escaping (for example `\f', `\"'). Other unusual characters are printed using an octal escape. Other printable characters (for -ls and -fls these are the characters between octal 041 and 0176) are printed as-is. -printf, -fprintf If the output is not going to a terminal, it is printed as-is. Otherwise, the result depends on which directive is in use. The directives %D, %F, %g, %G, %H, %Y, and %y expand to values which are not under control of files' owners, and so are printed as-is. The directives %a, %b, %c, %d, %i, %k, %m, %M, %n, %s, %t, %u and %U have values which are under the control of files' owners but which cannot be used to send arbitrary data to the terminal, and so these are printed as-is. The directives %f, %h, %l, %p and %P are quoted. This quoting is performed in the same way as for GNU ls. This is not the same quoting mechanism as the one used for -ls and -fls. If you are able to decide what format to use for the output of find then it is normally better to use `\0' as a terminator than to use newline, as file names can contain white space and newline characters. The setting of the LC_CTYPE environment variable is used to determine which characters need to be quoted. -print, -fprint Quoting is handled in the same way as for -printf and -fprintf. If you are using find in a script or in a situation where the matched files might have arbitrary names, you should consider using -print0 instead of -print. The -ok and -okdir actions print the current filename as-is. This may change in a future release. STANDARDS CONFORMANCE top For closest compliance to the POSIX standard, you should set the POSIXLY_CORRECT environment variable. The following options are specified in the POSIX standard (IEEE Std 1003.1-2008, 2016 Edition): -H This option is supported. -L This option is supported. -name This option is supported, but POSIX conformance depends on the POSIX conformance of the system's fnmatch(3) library function. As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) match a leading `.', because IEEE PASC interpretation 126 requires this. This is a change from previous versions of findutils. -type Supported. POSIX specifies `b', `c', `d', `l', `p', `f' and `s'. GNU find also supports `D', representing a Door, where the OS provides these. Furthermore, GNU find allows multiple types to be specified at once in a comma- separated list. -ok Supported. Interpretation of the response is according to the `yes' and `no' patterns selected by setting the LC_MESSAGES environment variable. When the POSIXLY_CORRECT environment variable is set, these patterns are taken system's definition of a positive (yes) or negative (no) response. See the system's documentation for nl_langinfo(3), in particular YESEXPR and NOEXPR. When POSIXLY_CORRECT is not set, the patterns are instead taken from find's own message catalogue. -newer Supported. If the file specified is a symbolic link, it is always dereferenced. This is a change from previous behaviour, which used to take the relevant time from the symbolic link; see the HISTORY section below. -perm Supported. If the POSIXLY_CORRECT environment variable is not set, some mode arguments (for example +a+x) which are not valid in POSIX are supported for backward- compatibility. Other primaries The primaries -atime, -ctime, -depth, -exec, -group, -links, -mtime, -nogroup, -nouser, -ok, -path, -print, -prune, -size, -user and -xdev are all supported. The POSIX standard specifies parentheses `(', `)', negation `!' and the logical AND/OR operators -a and -o. All other options, predicates, expressions and so forth are extensions beyond the POSIX standard. Many of these extensions are not unique to GNU find, however. The POSIX standard requires that find detects loops: The find utility shall detect infinite loops; that is, entering a previously visited directory that is an ancestor of the last file encountered. When it detects an infinite loop, find shall write a diagnostic message to standard error and shall either recover its position in the hierarchy or terminate. GNU find complies with these requirements. The link count of 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 optimise away the visiting of a subdirectory which is actually a link to an ancestor. Since find does not actually enter such a subdirectory, it is allowed to avoid emitting a diagnostic 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 you should use the POSIX-compliant option -depth instead. The POSIXLY_CORRECT environment variable does not affect the behaviour of the -regex or -iregex tests because those tests aren't specified in the POSIX standard. ENVIRONMENT VARIABLES top LANG Provides a default value for the internationalization variables that are unset or null. LC_ALL If set to a non-empty string value, override the values of all the other internationalization variables. LC_COLLATE The POSIX standard specifies that this variable affects the pattern matching to be used for the -name option. GNU find uses the fnmatch(3) library function, and so support for LC_COLLATE depends on the system library. This variable also affects the interpretation of the response to -ok; while the LC_MESSAGES variable selects the actual pattern used to interpret the response to -ok, the interpretation of any bracket expressions in the pattern will be affected by LC_COLLATE. LC_CTYPE This variable affects the treatment of character classes used in regular expressions and also with the -name test, if the system's fnmatch(3) library function supports this. This variable also affects the interpretation of any character classes in the regular expressions used to interpret the response to the prompt issued by -ok. The LC_CTYPE environment variable will also 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 the POSIXLY_CORRECT environment variable is set, this also determines the interpretation of the response to the prompt made by the -ok action. NLSPATH Determines the location of the internationalisation message catalogues. PATH Affects the directories which are searched to find the executables invoked by -exec, -execdir, -ok and -okdir. POSIXLY_CORRECT Determines the block size used by -ls and -fls. If POSIXLY_CORRECT is set, blocks are units of 512 bytes. Otherwise they are units of 1024 bytes. Setting this variable also turns off warning messages (that is, implies -nowarn) by default, because POSIX requires that apart from the output for -ok, all messages printed on stderr are 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 -printf and -fprintf. EXAMPLES top Simple `find|xargs` approach Find files named core in or below the directory /tmp and delete them. $ find /tmp -name core -type f -print | xargs /bin/rm -f Note that this will work incorrectly if there are any filenames containing newlines, single or double quotes, or spaces. Safer `find -print0 | xargs -0` approach Find files named core in or below the directory /tmp and delete them, processing filenames in such a way that file or directory names containing single or double quotes, spaces or newlines are correctly handled. $ find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f The -name test comes before the -type test in order to avoid having to call stat(2) on every file. Note that there is still a race between the time find traverses the hierarchy printing the matching filenames, and the time the process executed by xargs works with that file. Processing arbitrary starting points Given that another program proggy pre-filters and creates a huge NUL-separated list of files, process those as starting points, and find all regular, empty files among them: $ proggy | find -files0-from - -maxdepth 0 -type f -empty The use of `-files0-from -` means to read the names of the starting points from standard input, i.e., from the pipe; and -maxdepth 0 ensures that only explicitly those entries are examined without recursing into directories (in the case one of the starting points is one). Executing a command for each file Run file on every file in or below the current directory. $ find . -type f -exec file '{}' \; Notice that the braces are enclosed in single quote marks to protect them from interpretation as shell script punctuation. The semicolon is similarly protected by the use of a backslash, though single quotes could have been used in that case also. In many cases, one might prefer the `-exec ... +` or better the `-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. 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. 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. Given the following directory of projects and their associated SCM administrative directories, perform an efficient search for the projects' roots: $ find repo/ \ \( -exec test -d '{}/.svn' \; \ -or -exec test -d '{}/.git' \; \ -or -exec test -d '{}/CVS' \; \ \) -print -prune Sample output: repo/project1/CVS repo/gnu/project2/.svn repo/gnu/project3/.svn repo/gnu/project3/src/.svn repo/project4/.git In this example, -prune prevents unnecessary descent into directories that have already been discovered (for example we do not search project3/src because we already found project3/.svn), but ensures sibling directories (project2 and project3) are found. Other useful examples Search for several file types. $ find /tmp -type f,d,l Search for files, directories, and symbolic links in the 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 %f and %h format directives of the -printf action for some corner-cases. Here is an example including some output. $ find . .. / /tmp /tmp/TRACE compile compile/64/tests/find -maxdepth 0 -printf '[%h][%f]\n' [.][.] [.][..] [][/] [][tmp] [/tmp][TRACE] [.][compile] [compile/64/tests][find] EXIT STATUS top 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. 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 top 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 Programmers Manual, 1971-1986 provides some additional details; you can read it on-line at <https://www.cs.dartmouth.edu/~doug/reader.pdf>. 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. COMPATIBILITY top As of findutils-4.2.2, shell metacharacters (`*', `?' or `[]' for example) used in filename patterns match a leading `.', because IEEE POSIX interpretation 126 requires this. As of findutils-4.3.3, -perm /000 now matches all files instead of none. Nanosecond-resolution timestamps were implemented in findutils-4.3.3. As of findutils-4.3.11, the -delete action sets find's exit status to a nonzero value when it fails. However, find will not exit immediately. Previously, find's exit status was unaffected by the failure of -delete. Feature Added in Also occurs in -files0-from 4.9.0 -newerXY 4.3.3 BSD -D 4.3.1 -O 4.3.1 -readable 4.3.0 -writable 4.3.0 -executable 4.3.0 -regextype 4.2.24 -exec ... + 4.2.12 POSIX -execdir 4.2.12 BSD -okdir 4.2.12 -samefile 4.2.11 -H 4.2.5 POSIX -L 4.2.5 POSIX -P 4.2.5 BSD -delete 4.2.3 -quit 4.2.3 -d 4.2.3 BSD -wholename 4.2.0 -iwholename 4.2.0 -ignore_readdir_race 4.2.0 -fls 4.0 -ilname 3.8 -iname 3.8 -ipath 3.8 -iregex 3.8 The syntax -perm +MODE was removed in findutils-4.5.12, in favour of -perm /MODE. The +MODE syntax had been deprecated since findutils-4.2.21 which was released in 2005. NON-BUGS top Operator precedence surprises The command find . -name afile -o -name bfile -print will never print afile because this is actually equivalent to find . -name afile -o \( -name bfile -a -print \). Remember that the precedence of -a is higher than that of -o and when there is no operator specified between tests, -a is assumed. paths must precede expression error message $ find . -name *.c -print find: paths must precede expression find: possible unquoted pattern after predicate `-name'? This happens when the shell could expand the pattern *.c to more than one file name existing in the current directory, and passing the 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 top 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. The environment variable LC_COLLATE has no effect on the -ok action. REPORTING BUGS top 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 top Copyright 1990-2023 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 top 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 COLOPHON top This page is part of the findutils (find utilities) project. Information about the project can be found at http://www.gnu.org/software/findutils/. If you have a bug report for this manual page, see https://savannah.gnu.org/bugs/?group=findutils. This page was obtained from the project's upstream Git repository git://git.savannah.gnu.org/findutils.git on 2023-12-22. (At that time, the date of the most recent commit that was found in the repository was 2023-11-11.) If you discover any rendering problems in this HTML version of the page, or you believe there is a better or more up-to-date source for the page, or you have corrections or improvements to the information in this COLOPHON (which is not part of the original manual page), send a mail to man-pages@man7.org FIND(1) Pages that refer to this page: dpkg(1), dpkg-name(1), find-filter(1), grep(1), ippfind(1), locate(1), mkaf(1), pmlogger_daily(1), tar(1), updatedb(1), xargs(1), fts(3), proc(5), hier(7), symlink(7) HTML rendering created 2023-12-22 by Michael Kerrisk, author of The Linux Programming Interface. For details of in-depth Linux/UNIX system programming training courses that I teach, look here. Hosting by jambit GmbH. Task: search in the home folder for all the files with the name "monfichier" Bash Command:<START>find /home/ -name monfichier<END>